Merge pull request #184 from MilosKozak/nsclient

Internal nsclient
This commit is contained in:
Milos Kozak 2017-02-20 11:20:50 +01:00 committed by GitHub
commit 271fb00727
119 changed files with 2971 additions and 805 deletions

View file

@ -157,5 +157,11 @@ dependencies {
androidTestCompile "com.google.dexmaker:dexmaker:1.2" androidTestCompile "com.google.dexmaker:dexmaker:1.2"
androidTestCompile "com.google.dexmaker:dexmaker-mockito:1.2" androidTestCompile "com.google.dexmaker:dexmaker-mockito:1.2"
compile(name:'android-edittext-validator-v1.3.4-mod', ext:'aar') compile(name:'android-edittext-validator-v1.3.4-mod', ext:'aar')
compile ('io.socket:socket.io-client:0.8.3') {
// excluding org.json which is provided by Android
exclude group: 'org.json', module: 'json'
}
compile 'com.google.code.gson:gson:2.4'
compile 'com.google.guava:guava:18.0'
} }

View file

@ -14,6 +14,8 @@
<uses-permission android:name="android.permission.SEND_SMS" /> <uses-permission android:name="android.permission.SEND_SMS" />
<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.ACCESS_NETWORK_STATE" />
<uses-permission android:name="com.google.android.permission.PROVIDE_BACKGROUND" /> <uses-permission android:name="com.google.android.permission.PROVIDE_BACKGROUND" />
<!-- To receive data from xdrip. --> <!-- To receive data from xdrip. -->
@ -29,11 +31,14 @@
<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" />
<category android:name="android.intent.category.LAUNCHER" /> <category android:name="android.intent.category.LAUNCHER" />
</intent-filter> </intent-filter>
</activity> </activity>
<activity android:name=".PreferencesActivity" /> <activity android:name=".PreferencesActivity" />
<activity android:name=".plugins.Overview.Dialogs.BolusProgressHelperActivity" android:theme="@style/Theme.AppCompat.Translucent" /> <activity
android:name=".plugins.Overview.Dialogs.BolusProgressHelperActivity"
android:theme="@style/Theme.AppCompat.Translucent" />
<activity android:name=".AgreementActivity" /> <activity android:name=".AgreementActivity" />
<activity android:name=".plugins.DanaR.History.DanaRHistoryActivity" /> <activity android:name=".plugins.DanaR.History.DanaRHistoryActivity" />
<activity android:name=".plugins.DanaRKorean.History.DanaRHistoryActivity" /> <activity android:name=".plugins.DanaRKorean.History.DanaRHistoryActivity" />
@ -42,6 +47,7 @@
<activity android:name=".plugins.Overview.activities.QuickWizardListActivity"> <activity android:name=".plugins.Overview.activities.QuickWizardListActivity">
<intent-filter> <intent-filter>
<action android:name="info.nightscout.androidaps.plugins.Overview.activities.QuickWizardListActivity" /> <action android:name="info.nightscout.androidaps.plugins.Overview.activities.QuickWizardListActivity" />
<category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.DEFAULT" />
</intent-filter> </intent-filter>
</activity> </activity>
@ -68,20 +74,44 @@
<action android:name="com.eveningoutpost.dexdrip.BgEstimate" /> <action android:name="com.eveningoutpost.dexdrip.BgEstimate" />
<!-- Receiver from 640g uploader --> <!-- Receiver from 640g uploader -->
<action android:name="com.eveningoutpost.dexdrip.NS_EMULATOR" /> <action android:name="com.eveningoutpost.dexdrip.NS_EMULATOR" />
<!-- Auto start -->
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter> </intent-filter>
</receiver> </receiver>
<!-- Receiver keepalive, scheduled every 30 min --> <!-- Receiver keepalive, scheduled every 30 min -->
<receiver android:name=".receivers.KeepAliveReceiver" /> <receiver android:name=".receivers.KeepAliveReceiver" />
<!-- Auto start -->
<receiver
android:name=".plugins.NSClientInternal.receivers.AutoStartReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<!-- NSClient -->
<receiver
android:name=".plugins.NSClientInternal.receivers.RestartReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="info.nightscout.client.RESTART" />
</intent-filter>
</receiver>
<receiver
android:name=".plugins.NSClientInternal.receivers.DBAccessReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="info.nightscout.client.DBACCESS" />
</intent-filter>
</receiver>
<!-- Service processing incomming data --> <!-- Service processing incomming data -->
<service <service
android:name=".Services.DataService" android:name=".Services.DataService"
android:exported="false" /> android:exported="false" />
<!-- Service showing alert on screen -->
<service <service
android:name=".plugins.DanaR.Services.ExecutionService" android:name=".plugins.DanaR.Services.ExecutionService"
android:enabled="true" android:enabled="true"
@ -90,15 +120,23 @@
android:name=".plugins.DanaRKorean.Services.ExecutionService" android:name=".plugins.DanaRKorean.Services.ExecutionService"
android:enabled="true" android:enabled="true"
android:exported="false" /> android:exported="false" />
<service
<service android:name=".plugins.Wear.wearintegration.WatchUpdaterService" android:exported="true" > android:name=".plugins.Wear.wearintegration.WatchUpdaterService"
<intent-filter> <action android:name="com.google.android.gms.wearable.BIND_LISTENER" /> </intent-filter> android:exported="true">
<intent-filter>
<action android:name="com.google.android.gms.wearable.BIND_LISTENER" />
</intent-filter>
</service> </service>
<meta-data <meta-data
android:name="io.fabric.ApiKey" android:name="io.fabric.ApiKey"
android:value="59d462666c664c57b29e1d79ea123e01f8057cfa" /> android:value="59d462666c664c57b29e1d79ea123e01f8057cfa" />
<service
android:name=".plugins.NSClientInternal.services.NSClientService"
android:enabled="true"
android:exported="true" />
</application> </application>
</manifest> </manifest>

View file

@ -32,12 +32,12 @@ public class Constants {
public static final int CPP_MAX_PERCENTAGE = 200; public static final int CPP_MAX_PERCENTAGE = 200;
// Defaults for settings // Defaults for settings
public static final String MAX_BG_DEFAULT_MGDL = "180"; public static final Double MAX_BG_DEFAULT_MGDL = 180d;
public static final String MAX_BG_DEFAULT_MMOL = "10"; public static final Double MAX_BG_DEFAULT_MMOL = 10d;
public static final String MIN_BG_DEFAULT_MGDL = "100"; public static final Double MIN_BG_DEFAULT_MGDL = 100d;
public static final String MIN_BG_DEFAULT_MMOL = "5"; public static final Double MIN_BG_DEFAULT_MMOL = 5d;
public static final String TARGET_BG_DEFAULT_MGDL = "150"; public static final Double TARGET_BG_DEFAULT_MGDL = 150d;
public static final String TARGET_BG_DEFAULT_MMOL = "7"; public static final Double TARGET_BG_DEFAULT_MMOL = 7d;
// Very Hard Limits Ranges // Very Hard Limits Ranges
// First value is the Lowest and second value is the Highest a Limit can define // First value is the Lowest and second value is the Highest a Limit can define
@ -52,4 +52,7 @@ public class Constants {
//DanaR //DanaR
public static final double dailyLimitWarning = 0.95d; public static final double dailyLimitWarning = 0.95d;
//NSClientInternal
public static final int MAX_LOG_LINES = 100;
} }

View file

@ -36,10 +36,11 @@ import info.nightscout.androidaps.events.EventRefreshGui;
import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.tabs.SlidingTabLayout; import info.nightscout.androidaps.tabs.SlidingTabLayout;
import info.nightscout.androidaps.tabs.TabPageAdapter; import info.nightscout.androidaps.tabs.TabPageAdapter;
import info.nightscout.utils.LogDialog;
import info.nightscout.utils.ImportExportPrefs; import info.nightscout.utils.ImportExportPrefs;
import info.nightscout.utils.LocaleHelper; import info.nightscout.utils.LocaleHelper;
import info.nightscout.utils.LogDialog;
import info.nightscout.utils.PasswordProtection; import info.nightscout.utils.PasswordProtection;
import info.nightscout.utils.SP;
public class MainActivity extends AppCompatActivity { public class MainActivity extends AppCompatActivity {
private static Logger log = LoggerFactory.getLogger(MainActivity.class); private static Logger log = LoggerFactory.getLogger(MainActivity.class);
@ -86,7 +87,6 @@ public class MainActivity extends AppCompatActivity {
@Subscribe @Subscribe
public void onStatusEvent(final EventRefreshGui ev) { public void onStatusEvent(final EventRefreshGui ev) {
SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String lang = SP.getString("language", "en"); String lang = SP.getString("language", "en");
LocaleHelper.setLocale(getApplicationContext(), lang); LocaleHelper.setLocale(getApplicationContext(), lang);
runOnUiThread(new Runnable() { runOnUiThread(new Runnable() {

View file

@ -27,6 +27,7 @@ import info.nightscout.androidaps.plugins.DanaRKorean.DanaRKoreanFragment;
import info.nightscout.androidaps.plugins.LocalProfile.LocalProfileFragment; import info.nightscout.androidaps.plugins.LocalProfile.LocalProfileFragment;
import info.nightscout.androidaps.plugins.Loop.LoopFragment; import info.nightscout.androidaps.plugins.Loop.LoopFragment;
import info.nightscout.androidaps.plugins.MDI.MDIFragment; import info.nightscout.androidaps.plugins.MDI.MDIFragment;
import info.nightscout.androidaps.plugins.NSClientInternal.NSClientInternalFragment;
import info.nightscout.androidaps.plugins.NSProfile.NSProfileFragment; import info.nightscout.androidaps.plugins.NSProfile.NSProfileFragment;
import info.nightscout.androidaps.plugins.Objectives.ObjectivesFragment; import info.nightscout.androidaps.plugins.Objectives.ObjectivesFragment;
import info.nightscout.androidaps.plugins.OpenAPSAMA.OpenAPSAMAFragment; import info.nightscout.androidaps.plugins.OpenAPSAMA.OpenAPSAMAFragment;
@ -103,6 +104,7 @@ public class MainApp extends Application {
if (Config.WEAR) pluginsList.add(WearFragment.getPlugin(this)); if (Config.WEAR) pluginsList.add(WearFragment.getPlugin(this));
pluginsList.add(new PersistentNotificationPlugin(this)); pluginsList.add(new PersistentNotificationPlugin(this));
pluginsList.add(NSClientInternalFragment.getPlugin());
pluginsList.add(sConfigBuilder = ConfigBuilderFragment.getPlugin()); pluginsList.add(sConfigBuilder = ConfigBuilderFragment.getPlugin());

View file

@ -18,6 +18,7 @@ import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.plugins.DanaR.BluetoothDevicePreference; import info.nightscout.androidaps.plugins.DanaR.BluetoothDevicePreference;
import info.nightscout.androidaps.plugins.DanaR.DanaRPlugin; import info.nightscout.androidaps.plugins.DanaR.DanaRPlugin;
import info.nightscout.androidaps.plugins.DanaRKorean.DanaRKoreanPlugin; import info.nightscout.androidaps.plugins.DanaRKorean.DanaRKoreanPlugin;
import info.nightscout.androidaps.plugins.NSClientInternal.NSClientInternalPlugin;
import info.nightscout.androidaps.plugins.OpenAPSAMA.OpenAPSAMAPlugin; import info.nightscout.androidaps.plugins.OpenAPSAMA.OpenAPSAMAPlugin;
import info.nightscout.androidaps.plugins.VirtualPump.VirtualPumpPlugin; import info.nightscout.androidaps.plugins.VirtualPump.VirtualPumpPlugin;
import info.nightscout.androidaps.plugins.Wear.WearPlugin; import info.nightscout.androidaps.plugins.Wear.WearPlugin;
@ -36,7 +37,7 @@ public class PreferencesActivity extends PreferenceActivity implements SharedPre
@Override @Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
MainApp.bus().post(new EventPreferenceChange()); MainApp.bus().post(new EventPreferenceChange(key));
if (key.equals("language")) { if (key.equals("language")) {
String lang = sharedPreferences.getString("language", "en"); String lang = sharedPreferences.getString("language", "en");
LocaleHelper.setLocale(getApplicationContext(), lang); LocaleHelper.setLocale(getApplicationContext(), lang);
@ -111,6 +112,10 @@ public class PreferencesActivity extends PreferenceActivity implements SharedPre
if (virtualPumpPlugin != null && virtualPumpPlugin.isEnabled(PluginBase.PUMP)) { if (virtualPumpPlugin != null && virtualPumpPlugin.isEnabled(PluginBase.PUMP)) {
addPreferencesFromResource(R.xml.pref_virtualpump); addPreferencesFromResource(R.xml.pref_virtualpump);
} }
NSClientInternalPlugin nsClientInternalPlugin = (NSClientInternalPlugin) MainApp.getSpecificPlugin(NSClientInternalPlugin.class);
if (nsClientInternalPlugin != null && nsClientInternalPlugin.isEnabled(PluginBase.GENERAL)) {
addPreferencesFromResource(R.xml.pref_nsclientinternal);
}
if (Config.SMSCOMMUNICATORENABLED) if (Config.SMSCOMMUNICATORENABLED)
addPreferencesFromResource(R.xml.pref_smscommunicator); addPreferencesFromResource(R.xml.pref_smscommunicator);
addPreferencesFromResource(R.xml.pref_others); addPreferencesFromResource(R.xml.pref_others);

View file

@ -49,8 +49,8 @@ import info.nightscout.androidaps.plugins.SourceNSClient.SourceNSClientPlugin;
import info.nightscout.androidaps.plugins.SourceXdrip.SourceXdripPlugin; import info.nightscout.androidaps.plugins.SourceXdrip.SourceXdripPlugin;
import info.nightscout.androidaps.plugins.TempTargetRange.events.EventTempTargetRangeChange; import info.nightscout.androidaps.plugins.TempTargetRange.events.EventTempTargetRangeChange;
import info.nightscout.androidaps.receivers.DataReceiver; import info.nightscout.androidaps.receivers.DataReceiver;
import info.nightscout.client.data.NSProfile; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.client.data.NSSgv; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSSgv;
public class DataService extends IntentService { public class DataService extends IntentService {

View file

@ -11,11 +11,13 @@ public interface Intents {
String ACTION_NEW_MBG = "info.nightscout.client.NEW_MBG"; String ACTION_NEW_MBG = "info.nightscout.client.NEW_MBG";
String ACTION_NEW_CAL = "info.nightscout.client.NEW_CAL"; String ACTION_NEW_CAL = "info.nightscout.client.NEW_CAL";
String ACTION_NEW_STATUS = "info.nightscout.client.NEW_STATUS"; String ACTION_NEW_STATUS = "info.nightscout.client.NEW_STATUS";
String ACTION_QUEUE_STATUS = "info.nightscout.client.QUEUE_STATUS";
// App -> NSClient // App -> NSClient
String ACTION_DATABASE = "info.nightscout.client.DBACCESS"; String ACTION_DATABASE = "info.nightscout.client.DBACCESS";
String ACTION_RESTART = "info.nightscout.client.RESTART"; String ACTION_RESTART = "info.nightscout.client.RESTART";
String ACTION_RESEND = "info.nightscout.client.RESEND";
// xDrip -> App // xDrip -> App
String RECEIVER_PERMISSION = "com.eveningoutpost.dexdrip.permissions.RECEIVE_BG_ESTIMATE"; String RECEIVER_PERMISSION = "com.eveningoutpost.dexdrip.permissions.RECEIVE_BG_ESTIMATE";

View file

@ -6,9 +6,8 @@ import org.json.JSONObject;
import java.util.Date; import java.util.Date;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.client.data.NSProfile; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.utils.DateUtil; import info.nightscout.utils.DateUtil;
import info.nightscout.utils.Round; import info.nightscout.utils.Round;

View file

@ -10,7 +10,7 @@ import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.plugins.OpenAPSAMA.Autosens; import info.nightscout.androidaps.plugins.OpenAPSAMA.Autosens;
import info.nightscout.androidaps.plugins.OpenAPSAMA.AutosensResult; import info.nightscout.androidaps.plugins.OpenAPSAMA.AutosensResult;
import info.nightscout.androidaps.plugins.OpenAPSAMA.OpenAPSAMAPlugin; import info.nightscout.androidaps.plugins.OpenAPSAMA.OpenAPSAMAPlugin;
import info.nightscout.client.data.NSProfile; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
/** /**
* Created by mike on 04.01.2017. * Created by mike on 04.01.2017.

View file

@ -1,7 +1,5 @@
package info.nightscout.androidaps.data; package info.nightscout.androidaps.data;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.Html; import android.text.Html;
import android.text.Spanned; import android.text.Spanned;
@ -10,7 +8,7 @@ import org.json.JSONObject;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.client.data.NSProfile; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.utils.DecimalFormatter; import info.nightscout.utils.DecimalFormatter;
import info.nightscout.utils.Round; import info.nightscout.utils.Round;

View file

@ -10,7 +10,7 @@ import org.slf4j.LoggerFactory;
import java.util.Date; import java.util.Date;
import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.Constants;
import info.nightscout.client.data.NSSgv; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSSgv;
import info.nightscout.utils.DecimalFormatter; import info.nightscout.utils.DecimalFormatter;
@DatabaseTable(tableName = DatabaseHelper.DATABASE_BGREADINGS) @DatabaseTable(tableName = DatabaseHelper.DATABASE_BGREADINGS)

View file

@ -11,7 +11,7 @@ import java.util.Date;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.data.Iob; import info.nightscout.androidaps.data.Iob;
import info.nightscout.androidaps.data.IobTotal; import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.client.data.NSProfile; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.utils.DateUtil; import info.nightscout.utils.DateUtil;
import info.nightscout.utils.DecimalFormatter; import info.nightscout.utils.DecimalFormatter;

View file

@ -15,7 +15,7 @@ import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.data.Iob; import info.nightscout.androidaps.data.Iob;
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.Overview.graphExtensions.DataPointWithLabelInterface;
import info.nightscout.client.data.NSProfile; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.utils.DateUtil; import info.nightscout.utils.DateUtil;
import info.nightscout.utils.DecimalFormatter; import info.nightscout.utils.DecimalFormatter;

View file

@ -0,0 +1,8 @@
package info.nightscout.androidaps.events;
/**
* Created by mike on 17.02.2017.
*/
public class EventConfigBuilderChange {
}

View file

@ -1,6 +1,6 @@
package info.nightscout.androidaps.events; package info.nightscout.androidaps.events;
import info.nightscout.client.data.NSProfile; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
/** /**
* Created by mike on 04.06.2016. * Created by mike on 04.06.2016.

View file

@ -1,7 +1,25 @@
package info.nightscout.androidaps.events; package info.nightscout.androidaps.events;
import info.nightscout.androidaps.MainApp;
/** /**
* Created by mike on 19.06.2016. * Created by mike on 19.06.2016.
*/ */
public class EventPreferenceChange { public class EventPreferenceChange {
public String changedKey;
public EventPreferenceChange(String key) {
changedKey = key;
}
public EventPreferenceChange(int resourceID) {
changedKey = MainApp.sResources.getString(resourceID);
}
public boolean isChanged(int id) {
return changedKey.equals(MainApp.sResources.getString(id));
}
public boolean isChanged(String id) {
return changedKey.equals(id);
}
} }

View file

@ -0,0 +1,50 @@
package info.nightscout.androidaps.events;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
/**
* Created by mike on 19.02.2017.
*/
public class EventPumpStatusChanged {
public static final int CONNECTING = 0;
public static final int CONNECTED = 1;
public static final int PERFORMING = 2;
public static final int DISCONNECTING = 3;
public static final int DISCONNECTED = 4;
public int sStatus = DISCONNECTED;
public int sSecondsElapsed = 0;
public String sPerfomingAction = "";
public EventPumpStatusChanged(int status) {
sStatus = status;
sSecondsElapsed = 0;
}
public EventPumpStatusChanged(int status, int secondsElapsed) {
sStatus = status;
sSecondsElapsed = secondsElapsed;
}
public EventPumpStatusChanged(String action) {
sStatus = PERFORMING;
sSecondsElapsed = 0;
sPerfomingAction = action;
}
public String textStatus() {
if (sStatus == CONNECTING)
return String.format(MainApp.sResources.getString(R.string.danar_history_connectingfor), sSecondsElapsed);
else if (sStatus == CONNECTED)
return MainApp.sResources.getString(R.string.connected);
else if (sStatus == PERFORMING)
return sPerfomingAction;
else if (sStatus == DISCONNECTING)
return MainApp.sResources.getString(R.string.disconnecting);
else if (sStatus == DISCONNECTED)
return "";
return "";
}
}

View file

@ -2,7 +2,7 @@ package info.nightscout.androidaps.interfaces;
import android.support.annotation.Nullable; import android.support.annotation.Nullable;
import info.nightscout.client.data.NSProfile; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
/** /**
* Created by mike on 14.06.2016. * Created by mike on 14.06.2016.

View file

@ -8,8 +8,7 @@ import java.util.Date;
import info.nightscout.androidaps.data.PumpEnactResult; import info.nightscout.androidaps.data.PumpEnactResult;
import info.nightscout.androidaps.db.TempBasal; import info.nightscout.androidaps.db.TempBasal;
import info.nightscout.androidaps.plugins.Loop.APSResult; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.client.data.NSProfile;
/** /**
* Created by mike on 04.06.2016. * Created by mike on 04.06.2016.
@ -30,8 +29,8 @@ public interface PumpInterface {
int setNewBasalProfile(NSProfile profile); int setNewBasalProfile(NSProfile profile);
boolean isThisProfileSet(NSProfile profile); boolean isThisProfileSet(NSProfile profile);
Date lastStatusTime(); Date lastDataTime();
void updateStatus(String reason); void refreshDataFromPump(String reason);
double getBaseBasalRate(); // base basal rate, not temp basal double getBaseBasalRate(); // base basal rate, not temp basal
double getTempBasalAbsoluteRate(); double getTempBasalAbsoluteRate();
@ -52,7 +51,9 @@ public interface PumpInterface {
JSONObject getJSONStatus(); JSONObject getJSONStatus();
String deviceID(); String deviceID();
// Pump capabilities
PumpDescription getPumpDescription(); PumpDescription getPumpDescription();
public String shortStatus(boolean veryShort); // Short info for SMS, Wear etc
String shortStatus(boolean veryShort);
} }

View file

@ -28,6 +28,7 @@ import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.utils.DecimalFormatter; import info.nightscout.utils.DecimalFormatter;
import info.nightscout.utils.PlusMinusEditText; import info.nightscout.utils.PlusMinusEditText;
import info.nightscout.utils.SP;
import info.nightscout.utils.SafeParse; import info.nightscout.utils.SafeParse;
public class FillDialog extends DialogFragment implements OnClickListener { public class FillDialog extends DialogFragment implements OnClickListener {
@ -72,10 +73,9 @@ public class FillDialog extends DialogFragment implements OnClickListener {
Button button3 = (Button) view.findViewById(R.id.fill_preset_button3); Button button3 = (Button) view.findViewById(R.id.fill_preset_button3);
View divider = view.findViewById(R.id.fill_preset_divider); View divider = view.findViewById(R.id.fill_preset_divider);
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext()); amount1 = SP.getDouble("fill_button1", 0.3);
amount1 = SafeParse.stringToDouble(DecimalFormatter.to2Decimal(SafeParse.stringToDouble(sp.getString("fill_button1", "0.3")))); amount2 = SP.getDouble("fill_button2", 0d);
amount2 = SafeParse.stringToDouble(DecimalFormatter.to2Decimal(SafeParse.stringToDouble(sp.getString("fill_button2", "0")))); amount3 = SP.getDouble("fill_button3", 0d);
amount3 = SafeParse.stringToDouble(DecimalFormatter.to2Decimal(SafeParse.stringToDouble(sp.getString("fill_button3", "0"))));
if(amount1 >0) { if(amount1 >0) {
button1.setVisibility(View.VISIBLE); button1.setVisibility(View.VISIBLE);

View file

@ -23,7 +23,7 @@ import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.PumpEnactResult; import info.nightscout.androidaps.data.PumpEnactResult;
import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.client.data.NSProfile; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.utils.PlusMinusEditText; import info.nightscout.utils.PlusMinusEditText;
import info.nightscout.utils.SafeParse; import info.nightscout.utils.SafeParse;

View file

@ -3,11 +3,9 @@ package info.nightscout.androidaps.plugins.Careportal.Dialogs;
import android.app.Activity; import android.app.Activity;
import android.content.DialogInterface; import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle; import android.os.Bundle;
import android.os.Handler; import android.os.Handler;
import android.os.HandlerThread; import android.os.HandlerThread;
import android.preference.PreferenceManager;
import android.support.v4.app.DialogFragment; import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AlertDialog; import android.support.v7.app.AlertDialog;
@ -42,7 +40,6 @@ import java.util.ArrayList;
import java.util.Calendar; import java.util.Calendar;
import java.util.Date; import java.util.Date;
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;
@ -53,10 +50,11 @@ import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.plugins.Careportal.OptionsToShow; import info.nightscout.androidaps.plugins.Careportal.OptionsToShow;
import info.nightscout.androidaps.plugins.CircadianPercentageProfile.CircadianPercentageProfilePlugin; import info.nightscout.androidaps.plugins.CircadianPercentageProfile.CircadianPercentageProfilePlugin;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.androidaps.plugins.TempTargetRange.events.EventTempTargetRangeChange; import info.nightscout.androidaps.plugins.TempTargetRange.events.EventTempTargetRangeChange;
import info.nightscout.client.data.NSProfile;
import info.nightscout.utils.DateUtil; import info.nightscout.utils.DateUtil;
import info.nightscout.utils.PlusMinusEditText; import info.nightscout.utils.PlusMinusEditText;
import info.nightscout.utils.SP;
import info.nightscout.utils.SafeParse; import info.nightscout.utils.SafeParse;
import info.nightscout.utils.ToastUtils; import info.nightscout.utils.ToastUtils;
import info.nightscout.utils.Translator; import info.nightscout.utils.Translator;
@ -391,7 +389,6 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
JSONObject gatherData() { JSONObject gatherData() {
SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext());
String enteredBy = SP.getString("careportal_enteredby", ""); String enteredBy = SP.getString("careportal_enteredby", "");
JSONObject data = new JSONObject(); JSONObject data = new JSONObject();
try { try {

View file

@ -15,8 +15,9 @@ import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.ProfileInterface; import info.nightscout.androidaps.interfaces.ProfileInterface;
import info.nightscout.client.data.NSProfile; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.utils.DecimalFormatter; import info.nightscout.utils.DecimalFormatter;
import info.nightscout.utils.SP;
import info.nightscout.utils.SafeParse; import info.nightscout.utils.SafeParse;
import info.nightscout.utils.ToastUtils; import info.nightscout.utils.ToastUtils;
@ -66,7 +67,7 @@ public class CircadianPercentageProfilePlugin implements PluginBase, ProfileInte
@Override @Override
public String getNameShort() { public String getNameShort() {
String name = MainApp.sResources.getString(R.string.circadian_percentage_profile_shortname); String name = MainApp.sResources.getString(R.string.circadian_percentage_profile_shortname);
if (!name.trim().isEmpty()){ if (!name.trim().isEmpty()) {
//only if translation exists //only if translation exists
return name; return name;
} }
@ -125,75 +126,19 @@ public class CircadianPercentageProfilePlugin implements PluginBase, ProfileInte
void loadSettings() { void loadSettings() {
if (Config.logPrefsChange) if (Config.logPrefsChange)
log.debug("Loading stored settings"); log.debug("Loading stored settings");
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext());
if (settings.contains(SETTINGS_PREFIX + "mgdl")) mgdl = SP.getBoolean(SETTINGS_PREFIX + "mgdl", true);
try { mmol = SP.getBoolean(SETTINGS_PREFIX + "mmol", false);
mgdl = settings.getBoolean(SETTINGS_PREFIX + "mgdl", true); dia = SP.getDouble(SETTINGS_PREFIX + "dia", 3d);
} catch (Exception e) { targetLow = SP.getDouble(SETTINGS_PREFIX + "targetlow", 80d);
log.debug(e.getMessage()); targetHigh = SP.getDouble(SETTINGS_PREFIX + "targethigh", 120d);
} percentage = SP.getInt(SETTINGS_PREFIX + "percentage", 100);
else mgdl = true; timeshift = SP.getInt(SETTINGS_PREFIX + "timeshift", 0);
if (settings.contains(SETTINGS_PREFIX + "mmol"))
try {
mmol = settings.getBoolean(SETTINGS_PREFIX + "mmol", false);
} catch (Exception e) {
log.debug(e.getMessage());
}
else mmol = false;
if (settings.contains(SETTINGS_PREFIX + "dia"))
try {
dia = SafeParse.stringToDouble(settings.getString(SETTINGS_PREFIX + "dia", "3"));
} catch (Exception e) {
log.debug(e.getMessage());
}
else dia = 3d;
if (settings.contains(SETTINGS_PREFIX + "targetlow"))
try {
targetLow = SafeParse.stringToDouble(settings.getString(SETTINGS_PREFIX + "targetlow", "80"));
} catch (Exception e) {
log.debug(e.getMessage());
}
else targetLow = 80d;
if (settings.contains(SETTINGS_PREFIX + "targethigh"))
try {
targetHigh = SafeParse.stringToDouble(settings.getString(SETTINGS_PREFIX + "targethigh", "120"));
} catch (Exception e) {
log.debug(e.getMessage());
}
else targetHigh = 120d;
if (settings.contains(SETTINGS_PREFIX + "percentage"))
try {
percentage = SafeParse.stringToInt(settings.getString(SETTINGS_PREFIX + "percentage", "100"));
} catch (Exception e) {
log.debug(e.getMessage());
}
else percentage = 100;
if (settings.contains(SETTINGS_PREFIX + "timeshift"))
try {
timeshift = SafeParse.stringToInt(settings.getString(SETTINGS_PREFIX + "timeshift", "0"));
} catch (Exception e) {
log.debug(e.getMessage());
}
else timeshift = 0;
for (int i = 0; i < 24; i++) { for (int i = 0; i < 24; i++) {
try { basebasal[i] = SP.getDouble(SETTINGS_PREFIX + "basebasal" + i, basebasal[i]);
basebasal[i] = SafeParse.stringToDouble(settings.getString(SETTINGS_PREFIX + "basebasal" + i, DecimalFormatter.to2Decimal(basebasal[i]))); baseic[i] = SP.getDouble(SETTINGS_PREFIX + "baseic" + i, baseic[i]);
} catch (Exception e) { baseisf[i] = SP.getDouble(SETTINGS_PREFIX + "baseisf" + i, baseisf[i]);
log.debug(e.getMessage());
}
try {
baseic[i] = SafeParse.stringToDouble(settings.getString(SETTINGS_PREFIX + "baseic" + i, DecimalFormatter.to2Decimal(baseic[i])));
} catch (Exception e) {
log.debug(e.getMessage());
}
try {
baseisf[i] = SafeParse.stringToDouble(settings.getString(SETTINGS_PREFIX + "baseisf" + i, DecimalFormatter.to2Decimal(baseisf[i])));
} catch (Exception e) {
log.debug(e.getMessage());
}
} }
@ -259,7 +204,7 @@ public class CircadianPercentageProfilePlugin implements PluginBase, ProfileInte
} }
private void performLimitCheck() { private void performLimitCheck() {
if (percentage < Constants.CPP_MIN_PERCENTAGE || percentage > Constants.CPP_MAX_PERCENTAGE){ if (percentage < Constants.CPP_MIN_PERCENTAGE || percentage > Constants.CPP_MAX_PERCENTAGE) {
String msg = String.format(MainApp.sResources.getString(R.string.openapsma_valueoutofrange), "Profile-Percentage"); String msg = String.format(MainApp.sResources.getString(R.string.openapsma_valueoutofrange), "Profile-Percentage");
log.error(msg); log.error(msg);
MainApp.getConfigBuilder().uploadError(msg); MainApp.getConfigBuilder().uploadError(msg);
@ -289,13 +234,15 @@ public class CircadianPercentageProfilePlugin implements PluginBase, ProfileInte
return profileString(baseisf, 0, 100, false); return profileString(baseisf, 0, 100, false);
} }
String baseBasalString() {return profileString(basebasal, 0, 100, true);} String baseBasalString() {
return profileString(basebasal, 0, 100, true);
}
public double baseBasalSum(){ public double baseBasalSum() {
return sum(basebasal); return sum(basebasal);
} }
public double percentageBasalSum(){ public double percentageBasalSum() {
double result = 0; double result = 0;
for (int i = 0; i < basebasal.length; i++) { for (int i = 0; i < basebasal.length; i++) {
result += SafeParse.stringToDouble(DecimalFormatter.to2Decimal(basebasal[i] * percentage / 100d)); result += SafeParse.stringToDouble(DecimalFormatter.to2Decimal(basebasal[i] * percentage / 100d));
@ -304,7 +251,7 @@ public class CircadianPercentageProfilePlugin implements PluginBase, ProfileInte
} }
public static double sum(double values[]){ public static double sum(double values[]) {
double result = 0; double result = 0;
for (int i = 0; i < values.length; i++) { for (int i = 0; i < values.length; i++) {
result += values[i]; result += values[i];

View file

@ -20,6 +20,7 @@ import java.util.ArrayList;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.events.EventConfigBuilderChange;
import info.nightscout.androidaps.events.EventRefreshGui; import info.nightscout.androidaps.events.EventRefreshGui;
import info.nightscout.androidaps.interfaces.APSInterface; import info.nightscout.androidaps.interfaces.APSInterface;
import info.nightscout.androidaps.interfaces.BgSourceInterface; import info.nightscout.androidaps.interfaces.BgSourceInterface;
@ -197,6 +198,7 @@ public class ConfigBuilderFragment extends Fragment implements FragmentBase {
onEnabledCategoryChanged(plugin, type); onEnabledCategoryChanged(plugin, type);
configBuilderPlugin.storeSettings(); configBuilderPlugin.storeSettings();
MainApp.bus().post(new EventRefreshGui(true)); MainApp.bus().post(new EventRefreshGui(true));
MainApp.bus().post(new EventConfigBuilderChange());
getPlugin().logPluginStatus(); getPlugin().logPluginStatus();
} }
}); });

View file

@ -54,8 +54,8 @@ import info.nightscout.androidaps.plugins.Overview.Dialogs.BolusProgressHelperAc
import info.nightscout.androidaps.plugins.Overview.Notification; import info.nightscout.androidaps.plugins.Overview.Notification;
import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification; import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification;
import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification; import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification;
import info.nightscout.client.data.DbLogger; import info.nightscout.androidaps.plugins.NSClientInternal.data.DbLogger;
import info.nightscout.client.data.NSProfile; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.utils.DateUtil; import info.nightscout.utils.DateUtil;
/** /**
@ -390,13 +390,13 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain
} }
@Override @Override
public Date lastStatusTime() { public Date lastDataTime() {
return activePump.lastStatusTime(); return activePump.lastDataTime();
} }
@Override @Override
public void updateStatus(String reason) { public void refreshDataFromPump(String reason) {
activePump.updateStatus(reason); activePump.refreshDataFromPump(reason);
} }
@Override @Override
@ -482,7 +482,7 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain
carbs = applyCarbsConstraints(carbs); carbs = applyCarbsConstraints(carbs);
BolusProgressDialog bolusProgressDialog = null; BolusProgressDialog bolusProgressDialog = null;
if (context != null ) { if (context != null) {
bolusProgressDialog = new BolusProgressDialog(); bolusProgressDialog = new BolusProgressDialog();
bolusProgressDialog.setInsulin(insulin); bolusProgressDialog.setInsulin(insulin);
bolusProgressDialog.show(((AppCompatActivity) context).getSupportFragmentManager(), "BolusProgress"); bolusProgressDialog.show(((AppCompatActivity) context).getSupportFragmentManager(), "BolusProgress");
@ -682,7 +682,7 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain
public String deviceID() { public String deviceID() {
if (activePump != null) if (activePump != null)
return activePump.deviceID(); return activePump.deviceID();
else return "Unknown"; else return "No Pump active!";
} }
@Override @Override
@ -966,6 +966,8 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain
requested.put("temp", "absolute"); requested.put("temp", "absolute");
deviceStatus.enacted.put("requested", requested); deviceStatus.enacted.put("requested", requested);
} }
} else {
log.debug("OpenAPS data too old to upload");
} }
if (activePump != null) { if (activePump != null) {
deviceStatus.device = "openaps://" + deviceID(); deviceStatus.device = "openaps://" + deviceID();
@ -973,11 +975,9 @@ public class ConfigBuilderPlugin implements PluginBase, PumpInterface, Constrain
if (pumpstatus != null) { if (pumpstatus != null) {
deviceStatus.pump = getJSONStatus(); deviceStatus.pump = getJSONStatus();
} }
deviceStatus.created_at = DateUtil.toISOString(new Date());
deviceStatus.sendToNSClient();
} }
deviceStatus.created_at = DateUtil.toISOString(new Date());
deviceStatus.sendToNSClient();
} catch (JSONException e) { } catch (JSONException e) {
e.printStackTrace(); e.printStackTrace();
} }

View file

@ -24,13 +24,12 @@ 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.events.EventPreferenceChange; import info.nightscout.androidaps.events.EventPumpStatusChanged;
import info.nightscout.androidaps.events.EventTempBasalChange; import info.nightscout.androidaps.events.EventTempBasalChange;
import info.nightscout.androidaps.interfaces.FragmentBase; import info.nightscout.androidaps.interfaces.FragmentBase;
import info.nightscout.androidaps.plugins.DanaR.Dialogs.ProfileViewDialog; import info.nightscout.androidaps.plugins.DanaR.Dialogs.ProfileViewDialog;
import info.nightscout.androidaps.plugins.DanaR.History.DanaRHistoryActivity; import info.nightscout.androidaps.plugins.DanaR.History.DanaRHistoryActivity;
import info.nightscout.androidaps.plugins.DanaR.History.DanaRStatsActivity; import info.nightscout.androidaps.plugins.DanaR.History.DanaRStatsActivity;
import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRConnectionStatus;
import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRNewStatus; import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRNewStatus;
import info.nightscout.utils.DateUtil; import info.nightscout.utils.DateUtil;
import info.nightscout.utils.DecimalFormatter; import info.nightscout.utils.DecimalFormatter;
@ -166,18 +165,18 @@ public class DanaRFragment extends Fragment implements FragmentBase {
} }
@Subscribe @Subscribe
public void onStatusEvent(final EventDanaRConnectionStatus c) { public void onStatusEvent(final EventPumpStatusChanged c) {
Activity activity = getActivity(); Activity activity = getActivity();
if (activity != null) { if (activity != null) {
activity.runOnUiThread( activity.runOnUiThread(
new Runnable() { new Runnable() {
@Override @Override
public void run() { public void run() {
if (c.sStatus == EventDanaRConnectionStatus.CONNECTING) if (c.sStatus == EventPumpStatusChanged.CONNECTING)
btConnectionView.setText("{fa-bluetooth-b spin} " + c.sSecondsElapsed + "s"); btConnectionView.setText("{fa-bluetooth-b spin} " + c.sSecondsElapsed + "s");
else if (c.sStatus == EventDanaRConnectionStatus.CONNECTED) else if (c.sStatus == EventPumpStatusChanged.CONNECTED)
btConnectionView.setText("{fa-bluetooth}"); btConnectionView.setText("{fa-bluetooth}");
else else if (c.sStatus == EventPumpStatusChanged.DISCONNECTED)
btConnectionView.setText("{fa-bluetooth-b}"); btConnectionView.setText("{fa-bluetooth-b}");
} }
} }
@ -195,11 +194,6 @@ public class DanaRFragment extends Fragment implements FragmentBase {
updateGUI(); updateGUI();
} }
@Subscribe
public void onStatusEvent(final EventPreferenceChange s) {
updateGUI();
}
// GUI functions // GUI functions
private void updateGUI() { private void updateGUI() {
Activity activity = getActivity(); Activity activity = getActivity();

View file

@ -40,7 +40,7 @@ import info.nightscout.androidaps.plugins.NSProfile.NSProfilePlugin;
import info.nightscout.androidaps.plugins.Overview.Notification; import info.nightscout.androidaps.plugins.Overview.Notification;
import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification; import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification;
import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification; import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification;
import info.nightscout.client.data.NSProfile; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.utils.DateUtil; import info.nightscout.utils.DateUtil;
import info.nightscout.utils.DecimalFormatter; import info.nightscout.utils.DecimalFormatter;
import info.nightscout.utils.Round; import info.nightscout.utils.Round;
@ -285,12 +285,12 @@ public class DanaRPlugin implements PluginBase, PumpInterface, ConstraintsInterf
} }
@Override @Override
public Date lastStatusTime() { public Date lastDataTime() {
return getDanaRPump().lastConnection; return getDanaRPump().lastConnection;
} }
@Override @Override
public void updateStatus(String reason) { public void refreshDataFromPump(String reason) {
if (!isConnected() && !isConnecting()) { if (!isConnected() && !isConnecting()) {
doConnect(reason); doConnect(reason);
} }

View file

@ -1,8 +1,5 @@
package info.nightscout.androidaps.plugins.DanaR; package info.nightscout.androidaps.plugins.DanaR;
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;
@ -11,9 +8,9 @@ import java.text.DecimalFormat;
import java.util.Date; import java.util.Date;
import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R;
import info.nightscout.client.data.NSProfile; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.utils.SafeParse; import info.nightscout.utils.SP;
/** /**
* Created by mike on 04.07.2016. * Created by mike on 04.07.2016.
@ -122,8 +119,7 @@ public class DanaRPump {
// Evening / 17:0021:59 // Evening / 17:0021:59
// Night / 22:005:59 // Night / 22:005:59
SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext()); double dia = SP.getDouble(R.string.key_danarprofile_dia, 3d);
double dia = SafeParse.stringToDouble(SP.getString("danarprofile_dia", "3"));
try { try {
json.put("defaultProfile", PROFILE_PREFIX + (activeProfile + 1)); json.put("defaultProfile", PROFILE_PREFIX + (activeProfile + 1));

View file

@ -15,12 +15,10 @@ import org.slf4j.LoggerFactory;
import java.util.Date; import java.util.Date;
import info.nightscout.androidaps.MainActivity;
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.DanaR.DanaRFragment;
import info.nightscout.androidaps.plugins.DanaR.DanaRPlugin; import info.nightscout.androidaps.plugins.DanaR.DanaRPlugin;
import info.nightscout.client.data.NSProfile; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.utils.DecimalFormatter; import info.nightscout.utils.DecimalFormatter;
/** /**

View file

@ -32,19 +32,18 @@ import org.slf4j.LoggerFactory;
import java.sql.SQLException; 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.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.db.DanaRHistoryRecord; import info.nightscout.androidaps.db.DanaRHistoryRecord;
import info.nightscout.androidaps.events.EventPumpStatusChanged;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.DanaR.Services.ExecutionService; import info.nightscout.androidaps.plugins.DanaR.Services.ExecutionService;
import info.nightscout.androidaps.plugins.DanaR.comm.RecordTypes; import info.nightscout.androidaps.plugins.DanaR.comm.RecordTypes;
import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRConnectionStatus;
import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRSyncStatus; import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRSyncStatus;
import info.nightscout.client.data.NSProfile; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.utils.DateUtil; import info.nightscout.utils.DateUtil;
import info.nightscout.utils.DecimalFormatter; import info.nightscout.utils.DecimalFormatter;
import info.nightscout.utils.ToastUtils; import info.nightscout.utils.ToastUtils;
@ -307,7 +306,7 @@ public class DanaRHistoryActivity extends Activity {
case RecordTypes.RECORD_TYPE_DAILY: case RecordTypes.RECORD_TYPE_DAILY:
holder.dailybasal.setText(DecimalFormatter.to2Decimal(record.getRecordDailyBasal()) + "U"); holder.dailybasal.setText(DecimalFormatter.to2Decimal(record.getRecordDailyBasal()) + "U");
holder.dailybolus.setText(DecimalFormatter.to2Decimal(record.getRecordDailyBolus()) + "U"); holder.dailybolus.setText(DecimalFormatter.to2Decimal(record.getRecordDailyBolus()) + "U");
holder.dailytotal.setText(DecimalFormatter.to2Decimal(record.getRecordDailyBolus()+ record.getRecordDailyBasal()) + "U"); holder.dailytotal.setText(DecimalFormatter.to2Decimal(record.getRecordDailyBolus() + record.getRecordDailyBasal()) + "U");
holder.time.setText(DateUtil.dateString(record.getRecordDate())); holder.time.setText(DateUtil.dateString(record.getRecordDate()));
holder.time.setVisibility(View.VISIBLE); holder.time.setVisibility(View.VISIBLE);
holder.value.setVisibility(View.GONE); holder.value.setVisibility(View.GONE);
@ -435,21 +434,12 @@ public class DanaRHistoryActivity extends Activity {
} }
@Subscribe @Subscribe
public void onStatusEvent(final EventDanaRConnectionStatus c) { public void onStatusEvent(final EventPumpStatusChanged s) {
runOnUiThread( runOnUiThread(
new Runnable() { new Runnable() {
@Override @Override
public void run() { public void run() {
if (c.sStatus == EventDanaRConnectionStatus.CONNECTING) { statusView.setText(s.textStatus());
statusView.setText(String.format(getString(R.string.danar_history_connectingfor), c.sSecondsElapsed));
log.debug("EventDanaRConnectionStatus: " + "Connecting for " + c.sSecondsElapsed + "s");
} else if (c.sStatus == EventDanaRConnectionStatus.CONNECTED) {
statusView.setText(MainApp.sResources.getString(R.string.connected));
log.debug("EventDanaRConnectionStatus: Connected");
} else {
statusView.setText(MainApp.sResources.getString(R.string.disconnected));
log.debug("EventDanaRConnectionStatus: Disconnected");
}
} }
} }
); );

View file

@ -14,7 +14,7 @@ import info.nightscout.androidaps.db.DanaRHistoryRecord;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.DanaR.comm.RecordTypes; import info.nightscout.androidaps.plugins.DanaR.comm.RecordTypes;
import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRSyncStatus; import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRSyncStatus;
import info.nightscout.client.data.NSProfile; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.utils.DateUtil; import info.nightscout.utils.DateUtil;
import info.nightscout.utils.ToastUtils; import info.nightscout.utils.ToastUtils;

View file

@ -48,12 +48,12 @@ 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.DanaRHistoryRecord; import info.nightscout.androidaps.db.DanaRHistoryRecord;
import info.nightscout.androidaps.events.EventPumpStatusChanged;
import info.nightscout.androidaps.interfaces.ProfileInterface; import info.nightscout.androidaps.interfaces.ProfileInterface;
import info.nightscout.androidaps.plugins.CircadianPercentageProfile.CircadianPercentageProfilePlugin; import info.nightscout.androidaps.plugins.CircadianPercentageProfile.CircadianPercentageProfilePlugin;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.DanaR.Services.ExecutionService; import info.nightscout.androidaps.plugins.DanaR.Services.ExecutionService;
import info.nightscout.androidaps.plugins.DanaR.comm.RecordTypes; import info.nightscout.androidaps.plugins.DanaR.comm.RecordTypes;
import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRConnectionStatus;
import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRSyncStatus; import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRSyncStatus;
import info.nightscout.utils.DecimalFormatter; import info.nightscout.utils.DecimalFormatter;
import info.nightscout.utils.SafeParse; import info.nightscout.utils.SafeParse;
@ -68,11 +68,11 @@ public class DanaRStatsActivity extends Activity {
private Handler mHandler; private Handler mHandler;
private static HandlerThread mHandlerThread; private static HandlerThread mHandlerThread;
TextView statusView, statsMessage,totalBaseBasal2; TextView statusView, statsMessage, totalBaseBasal2;
EditText totalBaseBasal; EditText totalBaseBasal;
Button reloadButton; Button reloadButton;
LinearLayoutManager llm; LinearLayoutManager llm;
TableLayout tl,ctl,etl; TableLayout tl, ctl, etl;
String TBB; String TBB;
double magicNumber; double magicNumber;
DecimalFormat decimalFormat; DecimalFormat decimalFormat;
@ -118,15 +118,15 @@ public class DanaRStatsActivity extends Activity {
public boolean dispatchTouchEvent(MotionEvent event) { public boolean dispatchTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) { if (event.getAction() == MotionEvent.ACTION_DOWN) {
View myView = getCurrentFocus(); View myView = getCurrentFocus();
if ( myView instanceof EditText) { if (myView instanceof EditText) {
Rect rect = new Rect(); Rect rect = new Rect();
myView.getGlobalVisibleRect(rect); myView.getGlobalVisibleRect(rect);
if (!rect.contains((int)event.getRawX(), (int)event.getRawY())) { if (!rect.contains((int) event.getRawX(), (int) event.getRawY())) {
myView.clearFocus(); myView.clearFocus();
} }
} }
} }
return super.dispatchTouchEvent( event ); return super.dispatchTouchEvent(event);
} }
ServiceConnection mConnection = new ServiceConnection() { ServiceConnection mConnection = new ServiceConnection() {
@ -172,11 +172,11 @@ public class DanaRStatsActivity extends Activity {
totalBaseBasal.setText(TBB); totalBaseBasal.setText(TBB);
ProfileInterface pi = ConfigBuilderPlugin.getActiveProfile(); ProfileInterface pi = ConfigBuilderPlugin.getActiveProfile();
if (pi != null && pi instanceof CircadianPercentageProfilePlugin){ if (pi != null && pi instanceof CircadianPercentageProfilePlugin) {
double cppTBB = ((CircadianPercentageProfilePlugin)pi).baseBasalSum(); double cppTBB = ((CircadianPercentageProfilePlugin) pi).baseBasalSum();
totalBaseBasal.setText(decimalFormat.format(cppTBB)); totalBaseBasal.setText(decimalFormat.format(cppTBB));
SharedPreferences.Editor edit = preferences.edit(); SharedPreferences.Editor edit = preferences.edit();
edit.putString("TBB",totalBaseBasal.getText().toString()); edit.putString("TBB", totalBaseBasal.getText().toString());
edit.commit(); edit.commit();
TBB = preferences.getString("TBB", ""); TBB = preferences.getString("TBB", "");
} }
@ -312,7 +312,7 @@ public class DanaRStatsActivity extends Activity {
totalBaseBasal.setOnEditorActionListener(new TextView.OnEditorActionListener() { totalBaseBasal.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override @Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if(actionId== EditorInfo.IME_ACTION_DONE){ if (actionId == EditorInfo.IME_ACTION_DONE) {
totalBaseBasal.clearFocus(); totalBaseBasal.clearFocus();
return true; return true;
} }
@ -323,11 +323,11 @@ public class DanaRStatsActivity extends Activity {
totalBaseBasal.setOnFocusChangeListener(new View.OnFocusChangeListener() { totalBaseBasal.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override @Override
public void onFocusChange(View v, boolean hasFocus) { public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){ if (hasFocus) {
totalBaseBasal.getText().clear(); totalBaseBasal.getText().clear();
} else { } else {
SharedPreferences.Editor edit = preferences.edit(); SharedPreferences.Editor edit = preferences.edit();
edit.putString("TBB",totalBaseBasal.getText().toString()); edit.putString("TBB", totalBaseBasal.getText().toString());
edit.commit(); edit.commit();
TBB = preferences.getString("TBB", ""); TBB = preferences.getString("TBB", "");
loadDataFromDB(RecordTypes.RECORD_TYPE_DAILY); loadDataFromDB(RecordTypes.RECORD_TYPE_DAILY);
@ -362,15 +362,14 @@ public class DanaRStatsActivity extends Activity {
cleanTable(etl); cleanTable(etl);
DateFormat df = new SimpleDateFormat("dd.MM."); DateFormat df = new SimpleDateFormat("dd.MM.");
if(TextUtils.isEmpty(TBB)) { if (TextUtils.isEmpty(TBB)) {
totalBaseBasal.setError("Please Enter Total Base Basal"); totalBaseBasal.setError("Please Enter Total Base Basal");
return; return;
} } else {
else {
magicNumber = SafeParse.stringToDouble(TBB); magicNumber = SafeParse.stringToDouble(TBB);
} }
magicNumber *=2; magicNumber *= 2;
totalBaseBasal2.setText(decimalFormat.format(magicNumber)); totalBaseBasal2.setText(decimalFormat.format(magicNumber));
int i = 0; int i = 0;
@ -379,45 +378,45 @@ public class DanaRStatsActivity extends Activity {
double weighted05 = 0d; double weighted05 = 0d;
double weighted07 = 0d; double weighted07 = 0d;
for (DanaRHistoryRecord record: historyList) { for (DanaRHistoryRecord record : historyList) {
double tdd= record.getRecordDailyBolus() + record.getRecordDailyBasal(); double tdd = record.getRecordDailyBolus() + record.getRecordDailyBasal();
// Create the table row // Create the table row
TableRow tr = new TableRow(DanaRStatsActivity.this); TableRow tr = new TableRow(DanaRStatsActivity.this);
if(i%2!=0) tr.setBackgroundColor(Color.DKGRAY); if (i % 2 != 0) tr.setBackgroundColor(Color.DKGRAY);
tr.setId(100+i); tr.setId(100 + i);
tr.setLayoutParams(new TableLayout.LayoutParams( tr.setLayoutParams(new TableLayout.LayoutParams(
TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.MATCH_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT)); TableLayout.LayoutParams.WRAP_CONTENT));
// Here create the TextView dynamically // Here create the TextView dynamically
TextView labelDATE = new TextView(DanaRStatsActivity.this); TextView labelDATE = new TextView(DanaRStatsActivity.this);
labelDATE.setId(200+i); labelDATE.setId(200 + i);
labelDATE.setText(df.format(new Date(record.getRecordDate()))); labelDATE.setText(df.format(new Date(record.getRecordDate())));
labelDATE.setTextColor(Color.WHITE); labelDATE.setTextColor(Color.WHITE);
tr.addView(labelDATE); tr.addView(labelDATE);
TextView labelBASAL = new TextView(DanaRStatsActivity.this); TextView labelBASAL = new TextView(DanaRStatsActivity.this);
labelBASAL.setId(300+i); labelBASAL.setId(300 + i);
labelBASAL.setText(DecimalFormatter.to2Decimal(record.getRecordDailyBasal()) + " U"); labelBASAL.setText(DecimalFormatter.to2Decimal(record.getRecordDailyBasal()) + " U");
labelBASAL.setTextColor(Color.WHITE); labelBASAL.setTextColor(Color.WHITE);
tr.addView(labelBASAL); tr.addView(labelBASAL);
TextView labelBOLUS = new TextView(DanaRStatsActivity.this); TextView labelBOLUS = new TextView(DanaRStatsActivity.this);
labelBOLUS.setId(400+i); labelBOLUS.setId(400 + i);
labelBOLUS.setText(DecimalFormatter.to2Decimal(record.getRecordDailyBolus()) + " U"); labelBOLUS.setText(DecimalFormatter.to2Decimal(record.getRecordDailyBolus()) + " U");
labelBOLUS.setTextColor(Color.WHITE); labelBOLUS.setTextColor(Color.WHITE);
tr.addView(labelBOLUS); tr.addView(labelBOLUS);
TextView labelTDD = new TextView(DanaRStatsActivity.this); TextView labelTDD = new TextView(DanaRStatsActivity.this);
labelTDD.setId(500+i); labelTDD.setId(500 + i);
labelTDD.setText(DecimalFormatter.to2Decimal(tdd) + " U"); labelTDD.setText(DecimalFormatter.to2Decimal(tdd) + " U");
labelTDD.setTextColor(Color.WHITE); labelTDD.setTextColor(Color.WHITE);
tr.addView(labelTDD); tr.addView(labelTDD);
TextView labelRATIO = new TextView(DanaRStatsActivity.this); TextView labelRATIO = new TextView(DanaRStatsActivity.this);
labelRATIO.setId(600+i); labelRATIO.setId(600 + i);
labelRATIO.setText(Math.round(100*tdd/magicNumber) +" %"); labelRATIO.setText(Math.round(100 * tdd / magicNumber) + " %");
labelRATIO.setTextColor(Color.WHITE); labelRATIO.setTextColor(Color.WHITE);
tr.addView(labelRATIO); tr.addView(labelRATIO);
@ -431,28 +430,28 @@ public class DanaRStatsActivity extends Activity {
// Create the cumtable row // Create the cumtable row
TableRow ctr = new TableRow(DanaRStatsActivity.this); TableRow ctr = new TableRow(DanaRStatsActivity.this);
if(i%2==0) ctr.setBackgroundColor(Color.DKGRAY); if (i % 2 == 0) ctr.setBackgroundColor(Color.DKGRAY);
ctr.setId(700+i); ctr.setId(700 + i);
ctr.setLayoutParams(new TableLayout.LayoutParams( ctr.setLayoutParams(new TableLayout.LayoutParams(
TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.MATCH_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT)); TableLayout.LayoutParams.WRAP_CONTENT));
// Here create the TextView dynamically // Here create the TextView dynamically
TextView labelDAYS = new TextView(DanaRStatsActivity.this); TextView labelDAYS = new TextView(DanaRStatsActivity.this);
labelDAYS.setId(800+i); labelDAYS.setId(800 + i);
labelDAYS.setText("" + i); labelDAYS.setText("" + i);
labelDAYS.setTextColor(Color.WHITE); labelDAYS.setTextColor(Color.WHITE);
ctr.addView(labelDAYS); ctr.addView(labelDAYS);
TextView labelCUMTDD = new TextView(DanaRStatsActivity.this); TextView labelCUMTDD = new TextView(DanaRStatsActivity.this);
labelCUMTDD.setId(900+i); labelCUMTDD.setId(900 + i);
labelCUMTDD.setText(DecimalFormatter.to2Decimal(sum/i) + " U"); labelCUMTDD.setText(DecimalFormatter.to2Decimal(sum / i) + " U");
labelCUMTDD.setTextColor(Color.WHITE); labelCUMTDD.setTextColor(Color.WHITE);
ctr.addView(labelCUMTDD); ctr.addView(labelCUMTDD);
TextView labelCUMRATIO = new TextView(DanaRStatsActivity.this); TextView labelCUMRATIO = new TextView(DanaRStatsActivity.this);
labelCUMRATIO.setId(1000+i); labelCUMRATIO.setId(1000 + i);
labelCUMRATIO.setText(Math.round(100*sum/i/magicNumber) + " %"); labelCUMRATIO.setText(Math.round(100 * sum / i / magicNumber) + " %");
labelCUMRATIO.setTextColor(Color.WHITE); labelCUMRATIO.setTextColor(Color.WHITE);
ctr.addView(labelCUMRATIO); ctr.addView(labelCUMRATIO);
@ -462,7 +461,7 @@ public class DanaRStatsActivity extends Activity {
TableLayout.LayoutParams.WRAP_CONTENT)); TableLayout.LayoutParams.WRAP_CONTENT));
} }
if (historyList.size()<3 || !(df.format(new Date(historyList.get(0).getRecordDate())).equals(df.format(new Date(System.currentTimeMillis() - 1000*60*60*24))))){ if (historyList.size() < 3 || !(df.format(new Date(historyList.get(0).getRecordDate())).equals(df.format(new Date(System.currentTimeMillis() - 1000 * 60 * 60 * 24))))) {
statsMessage.setVisibility(View.VISIBLE); statsMessage.setVisibility(View.VISIBLE);
statsMessage.setText(getString(R.string.danar_stats_olddata_Message)); statsMessage.setText(getString(R.string.danar_stats_olddata_Message));
@ -474,38 +473,38 @@ public class DanaRStatsActivity extends Activity {
i = 0; i = 0;
for (DanaRHistoryRecord record: historyList) { for (DanaRHistoryRecord record : historyList) {
double tdd= record.getRecordDailyBolus() + record.getRecordDailyBasal(); double tdd = record.getRecordDailyBolus() + record.getRecordDailyBasal();
if(i == 0 ) { if (i == 0) {
weighted03 = tdd; weighted03 = tdd;
weighted05 = tdd; weighted05 = tdd;
weighted07 = tdd; weighted07 = tdd;
} else { } else {
weighted07 = (weighted07*0.3 + tdd*0.7); weighted07 = (weighted07 * 0.3 + tdd * 0.7);
weighted05 = (weighted05*0.5 + tdd*0.5); weighted05 = (weighted05 * 0.5 + tdd * 0.5);
weighted03 = (weighted03*0.7 + tdd*0.3); weighted03 = (weighted03 * 0.7 + tdd * 0.3);
} }
i++; i++;
} }
// Create the exptable row // Create the exptable row
TableRow etr = new TableRow(DanaRStatsActivity.this); TableRow etr = new TableRow(DanaRStatsActivity.this);
if(i%2!=0) etr.setBackgroundColor(Color.DKGRAY); if (i % 2 != 0) etr.setBackgroundColor(Color.DKGRAY);
etr.setId(1100+i); etr.setId(1100 + i);
etr.setLayoutParams(new TableLayout.LayoutParams( etr.setLayoutParams(new TableLayout.LayoutParams(
TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.MATCH_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT)); TableLayout.LayoutParams.WRAP_CONTENT));
// Here create the TextView dynamically // Here create the TextView dynamically
TextView labelWEIGHT = new TextView(DanaRStatsActivity.this); TextView labelWEIGHT = new TextView(DanaRStatsActivity.this);
labelWEIGHT.setId(1200+i); labelWEIGHT.setId(1200 + i);
labelWEIGHT.setText("0.3\n" + "0.5\n" + "0.7"); labelWEIGHT.setText("0.3\n" + "0.5\n" + "0.7");
labelWEIGHT.setTextColor(Color.WHITE); labelWEIGHT.setTextColor(Color.WHITE);
etr.addView(labelWEIGHT); etr.addView(labelWEIGHT);
TextView labelEXPTDD = new TextView(DanaRStatsActivity.this); TextView labelEXPTDD = new TextView(DanaRStatsActivity.this);
labelEXPTDD.setId(1300+i); labelEXPTDD.setId(1300 + i);
labelEXPTDD.setText(DecimalFormatter.to2Decimal(weighted03) labelEXPTDD.setText(DecimalFormatter.to2Decimal(weighted03)
+ " U\n" + DecimalFormatter.to2Decimal(weighted05) + " U\n" + DecimalFormatter.to2Decimal(weighted05)
+ " U\n" + DecimalFormatter.to2Decimal(weighted07) + " U"); + " U\n" + DecimalFormatter.to2Decimal(weighted07) + " U");
@ -513,10 +512,10 @@ public class DanaRStatsActivity extends Activity {
etr.addView(labelEXPTDD); etr.addView(labelEXPTDD);
TextView labelEXPRATIO = new TextView(DanaRStatsActivity.this); TextView labelEXPRATIO = new TextView(DanaRStatsActivity.this);
labelEXPRATIO.setId(1400+i); labelEXPRATIO.setId(1400 + i);
labelEXPRATIO.setText(Math.round(100*weighted03/magicNumber) +" %\n" labelEXPRATIO.setText(Math.round(100 * weighted03 / magicNumber) + " %\n"
+ Math.round(100*weighted05/magicNumber) +" %\n" + Math.round(100 * weighted05 / magicNumber) + " %\n"
+ Math.round(100*weighted07/magicNumber) +" %"); + Math.round(100 * weighted07 / magicNumber) + " %");
labelEXPRATIO.setTextColor(Color.WHITE); labelEXPRATIO.setTextColor(Color.WHITE);
etr.addView(labelEXPRATIO); etr.addView(labelEXPRATIO);
@ -549,21 +548,12 @@ public class DanaRStatsActivity extends Activity {
} }
@Subscribe @Subscribe
public void onStatusEvent(final EventDanaRConnectionStatus c) { public void onStatusEvent(final EventPumpStatusChanged c) {
runOnUiThread( runOnUiThread(
new Runnable() { new Runnable() {
@Override @Override
public void run() { public void run() {
if (c.sStatus == EventDanaRConnectionStatus.CONNECTING) { statusView.setText(c.textStatus());
statusView.setText(String.format(getString(R.string.danar_history_connectingfor), c.sSecondsElapsed));
log.debug("EventDanaRConnectionStatus: " + "Connecting for " + c.sSecondsElapsed + "s");
} else if (c.sStatus == EventDanaRConnectionStatus.CONNECTED) {
statusView.setText(MainApp.sResources.getString(R.string.connected));
log.debug("EventDanaRConnectionStatus: Connected");
} else {
statusView.setText(MainApp.sResources.getString(R.string.disconnected));
log.debug("EventDanaRConnectionStatus: Disconnected");
}
} }
} }
); );

View file

@ -33,8 +33,8 @@ import info.nightscout.androidaps.db.Treatment;
import info.nightscout.androidaps.events.EventAppExit; import info.nightscout.androidaps.events.EventAppExit;
import info.nightscout.androidaps.events.EventInitializationChanged; import info.nightscout.androidaps.events.EventInitializationChanged;
import info.nightscout.androidaps.events.EventPreferenceChange; import info.nightscout.androidaps.events.EventPreferenceChange;
import info.nightscout.androidaps.events.EventPumpStatusChanged;
import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.DanaR.DanaRPlugin; import info.nightscout.androidaps.plugins.DanaR.DanaRPlugin;
import info.nightscout.androidaps.plugins.DanaR.DanaRPump; import info.nightscout.androidaps.plugins.DanaR.DanaRPump;
import info.nightscout.androidaps.plugins.DanaR.SerialIOThread; import info.nightscout.androidaps.plugins.DanaR.SerialIOThread;
@ -78,18 +78,17 @@ import info.nightscout.androidaps.plugins.DanaR.comm.MsgStatusBolusExtended;
import info.nightscout.androidaps.plugins.DanaR.comm.MsgStatusTempBasal; import info.nightscout.androidaps.plugins.DanaR.comm.MsgStatusTempBasal;
import info.nightscout.androidaps.plugins.DanaR.comm.RecordTypes; import info.nightscout.androidaps.plugins.DanaR.comm.RecordTypes;
import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRBolusStart; import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRBolusStart;
import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRConnectionStatus;
import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRNewStatus; import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRNewStatus;
import info.nightscout.androidaps.plugins.Overview.Notification; import info.nightscout.androidaps.plugins.Overview.Notification;
import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification; import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification;
import info.nightscout.client.data.NSProfile; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.utils.SP;
import info.nightscout.utils.SafeParse; import info.nightscout.utils.SafeParse;
import info.nightscout.utils.ToastUtils; import info.nightscout.utils.ToastUtils;
public class ExecutionService extends Service { public class ExecutionService extends Service {
private static Logger log = LoggerFactory.getLogger(ExecutionService.class); private static Logger log = LoggerFactory.getLogger(ExecutionService.class);
private SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext());
private String devName; private String devName;
private SerialIOThread mSerialIOThread; private SerialIOThread mSerialIOThread;
@ -118,7 +117,7 @@ public class ExecutionService extends Service {
if (mSerialIOThread != null) { if (mSerialIOThread != null) {
mSerialIOThread.disconnect("BT disconnection broadcast"); mSerialIOThread.disconnect("BT disconnection broadcast");
} }
MainApp.bus().post(new EventDanaRConnectionStatus(EventDanaRConnectionStatus.DISCONNECTED, 0)); MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTED));
} }
} }
} }
@ -188,7 +187,7 @@ public class ExecutionService extends Service {
} }
public void connect(String from) { public void connect(String from) {
if (danaRPump.password != -1 && danaRPump.password != SafeParse.stringToInt(SP.getString("danar_password", "-1"))) { if (danaRPump.password != -1 && danaRPump.password != SP.getInt(R.string.key_danar_password, -1)) {
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.sResources.getString(R.string.wrongpumppassword), R.raw.error); ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.sResources.getString(R.string.wrongpumppassword), R.raw.error);
return; return;
} }
@ -208,7 +207,7 @@ public class ExecutionService extends Service {
long startTime = new Date().getTime(); long startTime = new Date().getTime();
while (!isConnected() && startTime + maxConnectionTime >= new Date().getTime()) { while (!isConnected() && startTime + maxConnectionTime >= new Date().getTime()) {
long secondsElapsed = (new Date().getTime() - startTime) / 1000L; long secondsElapsed = (new Date().getTime() - startTime) / 1000L;
MainApp.bus().post(new EventDanaRConnectionStatus(EventDanaRConnectionStatus.CONNECTING, (int) secondsElapsed)); MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.CONNECTING, (int) secondsElapsed));
if (Config.logDanaBTComm) if (Config.logDanaBTComm)
log.debug("connect waiting " + secondsElapsed + "sec from: " + from); log.debug("connect waiting " + secondsElapsed + "sec from: " + from);
try { try {
@ -227,18 +226,19 @@ public class ExecutionService extends Service {
mSerialIOThread.disconnect("Recreate SerialIOThread"); mSerialIOThread.disconnect("Recreate SerialIOThread");
} }
mSerialIOThread = new SerialIOThread(mRfcommSocket); mSerialIOThread = new SerialIOThread(mRfcommSocket);
MainApp.bus().post(new EventDanaRConnectionStatus(EventDanaRConnectionStatus.CONNECTED, 0)); MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.CONNECTED, 0));
if (!getPumpStatus()) { if (!getPumpStatus()) {
mSerialIOThread.disconnect("getPumpStatus failed"); mSerialIOThread.disconnect("getPumpStatus failed");
waitMsec(3000); waitMsec(3000);
if (!MainApp.getSpecificPlugin(DanaRPlugin.class).isEnabled(PluginBase.PUMP)) if (!MainApp.getSpecificPlugin(DanaRPlugin.class).isEnabled(PluginBase.PUMP))
return; return;
getBTSocketForSelectedPump(); getBTSocketForSelectedPump();
startTime = new Date().getTime();
} }
} }
} }
if (!isConnected()) { if (!isConnected()) {
MainApp.bus().post(new EventDanaRConnectionStatus(EventDanaRConnectionStatus.DISCONNECTED, 0)); MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTED));
log.error("Pump connection timed out"); log.error("Pump connection timed out");
} }
connectionInProgress = false; connectionInProgress = false;
@ -247,7 +247,7 @@ public class ExecutionService extends Service {
} }
private void getBTSocketForSelectedPump() { private void getBTSocketForSelectedPump() {
devName = SP.getString("danar_bt_name", ""); devName = SP.getString(MainApp.sResources.getString(R.string.key_danar_bt_name), "");
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter != null) { if (bluetoothAdapter != null) {
@ -280,7 +280,7 @@ public class ExecutionService extends Service {
private boolean getPumpStatus() { private boolean getPumpStatus() {
try { try {
MainApp.bus().post(new EventDanaRConnectionStatus(EventDanaRConnectionStatus.PERFORMING, 0, MainApp.sResources.getString(R.string.gettingpumpstatus))); MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.gettingpumpstatus)));
MsgStatus statusMsg = new MsgStatus(); MsgStatus statusMsg = new MsgStatus();
MsgStatusBasic statusBasicMsg = new MsgStatusBasic(); MsgStatusBasic statusBasicMsg = new MsgStatusBasic();
MsgStatusTempBasal tempStatusMsg = new MsgStatusTempBasal(); MsgStatusTempBasal tempStatusMsg = new MsgStatusTempBasal();
@ -341,7 +341,7 @@ public class ExecutionService extends Service {
danaRPump.lastConnection = now; danaRPump.lastConnection = now;
MainApp.bus().post(new EventDanaRNewStatus()); MainApp.bus().post(new EventDanaRNewStatus());
MainApp.bus().post(new EventInitializationChanged()); MainApp.bus().post(new EventInitializationChanged());
MainApp.getConfigBuilder().uploadDeviceStatus(60); MainApp.getConfigBuilder().uploadDeviceStatus(15);
if (danaRPump.dailyTotalUnits > danaRPump.maxDailyTotalUnits * Constants.dailyLimitWarning ) { if (danaRPump.dailyTotalUnits > danaRPump.maxDailyTotalUnits * Constants.dailyLimitWarning ) {
log.debug("Approaching daily limit: " + danaRPump.dailyTotalUnits + "/" + danaRPump.maxDailyTotalUnits); log.debug("Approaching daily limit: " + danaRPump.dailyTotalUnits + "/" + danaRPump.maxDailyTotalUnits);
Notification reportFail = new Notification(Notification.APPROACHING_DAILY_LIMIT, MainApp.sResources.getString(R.string.approachingdailylimit), Notification.URGENT); Notification reportFail = new Notification(Notification.APPROACHING_DAILY_LIMIT, MainApp.sResources.getString(R.string.approachingdailylimit), Notification.URGENT);
@ -357,46 +357,46 @@ public class ExecutionService extends Service {
public boolean tempBasal(int percent, int durationInHours) { public boolean tempBasal(int percent, int durationInHours) {
connect("tempBasal"); connect("tempBasal");
if (!isConnected()) return false; if (!isConnected()) return false;
MainApp.bus().post(new EventDanaRConnectionStatus(EventDanaRConnectionStatus.PERFORMING, 0, MainApp.sResources.getString(R.string.settingtempbasal))); MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.settingtempbasal)));
mSerialIOThread.sendMessage(new MsgSetTempBasalStart(percent, durationInHours)); mSerialIOThread.sendMessage(new MsgSetTempBasalStart(percent, durationInHours));
mSerialIOThread.sendMessage(new MsgStatusTempBasal()); mSerialIOThread.sendMessage(new MsgStatusTempBasal());
MainApp.bus().post(new EventDanaRConnectionStatus(EventDanaRConnectionStatus.PERFORMING, 0, MainApp.sResources.getString(R.string.disconnecting))); MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING));
return true; return true;
} }
public boolean tempBasalStop() { public boolean tempBasalStop() {
connect("tempBasalStop"); connect("tempBasalStop");
if (!isConnected()) return false; if (!isConnected()) return false;
MainApp.bus().post(new EventDanaRConnectionStatus(EventDanaRConnectionStatus.PERFORMING, 0, MainApp.sResources.getString(R.string.stoppingtempbasal))); MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.stoppingtempbasal)));
mSerialIOThread.sendMessage(new MsgSetTempBasalStop()); mSerialIOThread.sendMessage(new MsgSetTempBasalStop());
mSerialIOThread.sendMessage(new MsgStatusTempBasal()); mSerialIOThread.sendMessage(new MsgStatusTempBasal());
MainApp.bus().post(new EventDanaRConnectionStatus(EventDanaRConnectionStatus.PERFORMING, 0, MainApp.sResources.getString(R.string.disconnecting))); MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING));
return true; return true;
} }
public boolean extendedBolus(double insulin, int durationInHalfHours) { public boolean extendedBolus(double insulin, int durationInHalfHours) {
connect("extendedBolus"); connect("extendedBolus");
if (!isConnected()) return false; if (!isConnected()) return false;
MainApp.bus().post(new EventDanaRConnectionStatus(EventDanaRConnectionStatus.PERFORMING, 0, MainApp.sResources.getString(R.string.settingextendedbolus))); MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.settingextendedbolus)));
mSerialIOThread.sendMessage(new MsgSetExtendedBolusStart(insulin, (byte) (durationInHalfHours & 0xFF))); mSerialIOThread.sendMessage(new MsgSetExtendedBolusStart(insulin, (byte) (durationInHalfHours & 0xFF)));
mSerialIOThread.sendMessage(new MsgStatusBolusExtended()); mSerialIOThread.sendMessage(new MsgStatusBolusExtended());
MainApp.bus().post(new EventDanaRConnectionStatus(EventDanaRConnectionStatus.PERFORMING, 0, MainApp.sResources.getString(R.string.disconnecting))); MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING));
return true; return true;
} }
public boolean extendedBolusStop() { public boolean extendedBolusStop() {
connect("extendedBolusStop"); connect("extendedBolusStop");
if (!isConnected()) return false; if (!isConnected()) return false;
MainApp.bus().post(new EventDanaRConnectionStatus(EventDanaRConnectionStatus.PERFORMING, 0, MainApp.sResources.getString(R.string.stoppingextendedbolus))); MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.stoppingextendedbolus)));
mSerialIOThread.sendMessage(new MsgSetExtendedBolusStop()); mSerialIOThread.sendMessage(new MsgSetExtendedBolusStop());
mSerialIOThread.sendMessage(new MsgStatusBolusExtended()); mSerialIOThread.sendMessage(new MsgStatusBolusExtended());
MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING));
return true; return true;
} }
public boolean bolus(Double amount, int carbs, Treatment t) { public boolean bolus(Double amount, int carbs, Treatment t) {
bolusingTreatment = t; bolusingTreatment = t;
MsgBolusStart start = new MsgBolusStart(amount); MsgBolusStart start = new MsgBolusStart(amount);
MsgBolusProgress progress = new MsgBolusProgress(amount, t); // initialize static variables
MsgBolusStop stop = new MsgBolusStop(amount, t); MsgBolusStop stop = new MsgBolusStop(amount, t);
connect("bolus"); connect("bolus");
@ -406,6 +406,7 @@ public class ExecutionService extends Service {
Calendar time = Calendar.getInstance(); Calendar time = Calendar.getInstance();
mSerialIOThread.sendMessage(new MsgSetCarbsEntry(time, carbs)); mSerialIOThread.sendMessage(new MsgSetCarbsEntry(time, carbs));
} }
MsgBolusProgress progress = new MsgBolusProgress(amount, t); // initialize static variables
MainApp.bus().post(new EventDanaRBolusStart()); MainApp.bus().post(new EventDanaRBolusStart());
if (!stop.stopped) { if (!stop.stopped) {
@ -416,7 +417,7 @@ public class ExecutionService extends Service {
} }
while (!stop.stopped && !start.failed) { while (!stop.stopped && !start.failed) {
waitMsec(100); waitMsec(100);
if (progress.lastReceive != 0 && (new Date().getTime() - progress.lastReceive) > 5 * 1000L) { // if i didn't receive status for more than 5 sec expecting broken comm if ((new Date().getTime() - progress.lastReceive) > 5 * 1000L) { // if i didn't receive status for more than 5 sec expecting broken comm
stop.stopped = true; stop.stopped = true;
stop.forced = true; stop.forced = true;
log.debug("Communication stopped"); log.debug("Communication stopped");
@ -501,7 +502,7 @@ public class ExecutionService extends Service {
public boolean updateBasalsInPump(final NSProfile profile) { public boolean updateBasalsInPump(final NSProfile profile) {
connect("updateBasalsInPump"); connect("updateBasalsInPump");
if (!isConnected()) return false; if (!isConnected()) return false;
MainApp.bus().post(new EventDanaRConnectionStatus(EventDanaRConnectionStatus.PERFORMING, 0, MainApp.sResources.getString(R.string.updatingbasalrates))); MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.updatingbasalrates)));
double[] basal = buildDanaRProfileRecord(profile); double[] basal = buildDanaRProfileRecord(profile);
MsgSetBasalProfile msgSet = new MsgSetBasalProfile((byte) 0, basal); MsgSetBasalProfile msgSet = new MsgSetBasalProfile((byte) 0, basal);
mSerialIOThread.sendMessage(msgSet); mSerialIOThread.sendMessage(msgSet);
@ -509,7 +510,7 @@ public class ExecutionService extends Service {
mSerialIOThread.sendMessage(msgActivate); mSerialIOThread.sendMessage(msgActivate);
danaRPump.lastSettingsRead = new Date(0); // force read full settings danaRPump.lastSettingsRead = new Date(0); // force read full settings
getPumpStatus(); getPumpStatus();
MainApp.bus().post(new EventDanaRConnectionStatus(EventDanaRConnectionStatus.PERFORMING, 0, MainApp.sResources.getString(R.string.disconnecting))); MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING));
return true; return true;
} }

View file

@ -30,7 +30,7 @@ public class MsgBolusProgress extends MessageBase {
this(); this();
this.amount = amount; this.amount = amount;
this.t = t; this.t = t;
lastReceive = 0; lastReceive = new Date().getTime();
} }
@Override @Override

View file

@ -27,7 +27,7 @@ public class MsgSetCarbsEntry extends MessageBase {
AddParamByte((byte) 0x43); //?? AddParamByte((byte) 0x43); //??
AddParamInt(amount); AddParamInt(amount);
if (Config.logDanaMessageDetail) if (Config.logDanaMessageDetail)
log.debug("Set carb entry: " + amount + " date " + time.toString()); log.debug("Set carb entry: " + amount + " date " + time.getTime().toString());
} }
@Override @Override

View file

@ -1,23 +0,0 @@
package info.nightscout.androidaps.plugins.DanaR.events;
public class EventDanaRConnectionStatus {
public static final int CONNECTING = 0;
public static final int CONNECTED = 1;
public static final int DISCONNECTED = 2;
public static final int PERFORMING = 3;
public int sStatus = DISCONNECTED;
public int sSecondsElapsed = 0;
public String sAction = "";
public EventDanaRConnectionStatus(int status, int secondsElapsed) {
sStatus = status;
sSecondsElapsed = secondsElapsed;
}
public EventDanaRConnectionStatus(int status, int secondsElapsed, String action) {
sStatus = status;
sSecondsElapsed = secondsElapsed;
sAction = action;
}
}

View file

@ -24,11 +24,10 @@ 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.events.EventPreferenceChange; import info.nightscout.androidaps.events.EventPumpStatusChanged;
import info.nightscout.androidaps.events.EventTempBasalChange; import info.nightscout.androidaps.events.EventTempBasalChange;
import info.nightscout.androidaps.interfaces.FragmentBase; import info.nightscout.androidaps.interfaces.FragmentBase;
import info.nightscout.androidaps.plugins.DanaR.Dialogs.ProfileViewDialog; import info.nightscout.androidaps.plugins.DanaR.Dialogs.ProfileViewDialog;
import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRConnectionStatus;
import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRNewStatus; import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRNewStatus;
import info.nightscout.androidaps.plugins.DanaRKorean.History.DanaRHistoryActivity; import info.nightscout.androidaps.plugins.DanaRKorean.History.DanaRHistoryActivity;
import info.nightscout.androidaps.plugins.DanaRKorean.History.DanaRStatsActivity; import info.nightscout.androidaps.plugins.DanaRKorean.History.DanaRStatsActivity;
@ -163,18 +162,18 @@ public class DanaRKoreanFragment extends Fragment implements FragmentBase {
} }
@Subscribe @Subscribe
public void onStatusEvent(final EventDanaRConnectionStatus c) { public void onStatusEvent(final EventPumpStatusChanged c) {
Activity activity = getActivity(); Activity activity = getActivity();
if (activity != null) { if (activity != null) {
activity.runOnUiThread( activity.runOnUiThread(
new Runnable() { new Runnable() {
@Override @Override
public void run() { public void run() {
if (c.sStatus == EventDanaRConnectionStatus.CONNECTING) if (c.sStatus == EventPumpStatusChanged.CONNECTING)
btConnectionView.setText("{fa-bluetooth-b spin} " + c.sSecondsElapsed + "s"); btConnectionView.setText("{fa-bluetooth-b spin} " + c.sSecondsElapsed + "s");
else if (c.sStatus == EventDanaRConnectionStatus.CONNECTED) else if (c.sStatus == EventPumpStatusChanged.CONNECTED)
btConnectionView.setText("{fa-bluetooth}"); btConnectionView.setText("{fa-bluetooth}");
else else if (c.sStatus == EventPumpStatusChanged.DISCONNECTED)
btConnectionView.setText("{fa-bluetooth-b}"); btConnectionView.setText("{fa-bluetooth-b}");
} }
} }
@ -192,11 +191,6 @@ public class DanaRKoreanFragment extends Fragment implements FragmentBase {
updateGUI(); updateGUI();
} }
@Subscribe
public void onStatusEvent(final EventPreferenceChange s) {
updateGUI();
}
// GUI functions // GUI functions
private void updateGUI() { private void updateGUI() {

View file

@ -40,7 +40,7 @@ import info.nightscout.androidaps.plugins.NSProfile.NSProfilePlugin;
import info.nightscout.androidaps.plugins.Overview.Notification; import info.nightscout.androidaps.plugins.Overview.Notification;
import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification; import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification;
import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification; import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification;
import info.nightscout.client.data.NSProfile; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.utils.DateUtil; import info.nightscout.utils.DateUtil;
import info.nightscout.utils.DecimalFormatter; import info.nightscout.utils.DecimalFormatter;
import info.nightscout.utils.Round; import info.nightscout.utils.Round;
@ -72,6 +72,8 @@ public class DanaRKoreanPlugin implements PluginBase, PumpInterface, Constraints
return sDanaRKoreanPump; return sDanaRKoreanPump;
} }
String textStatus = "";
public DanaRKoreanPlugin() { public DanaRKoreanPlugin() {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext()); SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext());
useExtendedBoluses = sharedPreferences.getBoolean("danar_useextended", false); useExtendedBoluses = sharedPreferences.getBoolean("danar_useextended", false);
@ -285,12 +287,12 @@ public class DanaRKoreanPlugin implements PluginBase, PumpInterface, Constraints
} }
@Override @Override
public Date lastStatusTime() { public Date lastDataTime() {
return getDanaRPump().lastConnection; return getDanaRPump().lastConnection;
} }
@Override @Override
public void updateStatus(String reason) { public void refreshDataFromPump(String reason) {
if (!isConnected() && !isConnecting()) { if (!isConnected() && !isConnecting()) {
doConnect(reason); doConnect(reason);
} }

View file

@ -1,8 +1,5 @@
package info.nightscout.androidaps.plugins.DanaRKorean; package info.nightscout.androidaps.plugins.DanaRKorean;
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;
@ -11,9 +8,9 @@ import java.text.DecimalFormat;
import java.util.Date; import java.util.Date;
import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R;
import info.nightscout.client.data.NSProfile; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.utils.SafeParse; import info.nightscout.utils.SP;
/** /**
* Created by mike on 04.07.2016. * Created by mike on 04.07.2016.
@ -115,8 +112,7 @@ public class DanaRKoreanPump {
// Evening / 17:0021:59 // Evening / 17:0021:59
// Night / 22:005:59 // Night / 22:005:59
SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext()); double dia = SP.getDouble(R.string.key_danarprofile_dia, 3d);
double dia = SafeParse.stringToDouble(SP.getString("danarprofile_dia", "3"));
try { try {
json.put("defaultProfile", PROFILE_PREFIX + (activeProfile + 1)); json.put("defaultProfile", PROFILE_PREFIX + (activeProfile + 1));

View file

@ -32,20 +32,19 @@ import org.slf4j.LoggerFactory;
import java.sql.SQLException; 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.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.db.DanaRHistoryRecord; import info.nightscout.androidaps.db.DanaRHistoryRecord;
import info.nightscout.androidaps.events.EventPumpStatusChanged;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.DanaR.History.DanaRNSHistorySync; import info.nightscout.androidaps.plugins.DanaR.History.DanaRNSHistorySync;
import info.nightscout.androidaps.plugins.DanaR.comm.RecordTypes; import info.nightscout.androidaps.plugins.DanaR.comm.RecordTypes;
import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRConnectionStatus;
import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRSyncStatus; import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRSyncStatus;
import info.nightscout.androidaps.plugins.DanaRKorean.Services.ExecutionService; import info.nightscout.androidaps.plugins.DanaRKorean.Services.ExecutionService;
import info.nightscout.client.data.NSProfile; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.utils.DateUtil; import info.nightscout.utils.DateUtil;
import info.nightscout.utils.DecimalFormatter; import info.nightscout.utils.DecimalFormatter;
import info.nightscout.utils.ToastUtils; import info.nightscout.utils.ToastUtils;
@ -306,7 +305,7 @@ public class DanaRHistoryActivity extends Activity {
case RecordTypes.RECORD_TYPE_DAILY: case RecordTypes.RECORD_TYPE_DAILY:
holder.dailybasal.setText(DecimalFormatter.to2Decimal(record.getRecordDailyBasal()) + "U"); holder.dailybasal.setText(DecimalFormatter.to2Decimal(record.getRecordDailyBasal()) + "U");
holder.dailybolus.setText(DecimalFormatter.to2Decimal(record.getRecordDailyBolus()) + "U"); holder.dailybolus.setText(DecimalFormatter.to2Decimal(record.getRecordDailyBolus()) + "U");
holder.dailytotal.setText(DecimalFormatter.to2Decimal(record.getRecordDailyBolus()+ record.getRecordDailyBasal()) + "U"); holder.dailytotal.setText(DecimalFormatter.to2Decimal(record.getRecordDailyBolus() + record.getRecordDailyBasal()) + "U");
holder.time.setText(DateUtil.dateString(record.getRecordDate())); holder.time.setText(DateUtil.dateString(record.getRecordDate()));
holder.time.setVisibility(View.VISIBLE); holder.time.setVisibility(View.VISIBLE);
holder.value.setVisibility(View.GONE); holder.value.setVisibility(View.GONE);
@ -434,21 +433,12 @@ public class DanaRHistoryActivity extends Activity {
} }
@Subscribe @Subscribe
public void onStatusEvent(final EventDanaRConnectionStatus c) { public void onStatusEvent(final EventPumpStatusChanged c) {
runOnUiThread( runOnUiThread(
new Runnable() { new Runnable() {
@Override @Override
public void run() { public void run() {
if (c.sStatus == EventDanaRConnectionStatus.CONNECTING) { statusView.setText(c.textStatus());
statusView.setText(String.format(getString(R.string.danar_history_connectingfor), c.sSecondsElapsed));
log.debug("EventDanaRConnectionStatus: " + "Connecting for " + c.sSecondsElapsed + "s");
} else if (c.sStatus == EventDanaRConnectionStatus.CONNECTED) {
statusView.setText(MainApp.sResources.getString(R.string.connected));
log.debug("EventDanaRConnectionStatus: Connected");
} else {
statusView.setText(MainApp.sResources.getString(R.string.disconnected));
log.debug("EventDanaRConnectionStatus: Disconnected");
}
} }
} }
); );

View file

@ -48,11 +48,11 @@ 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.DanaRHistoryRecord; import info.nightscout.androidaps.db.DanaRHistoryRecord;
import info.nightscout.androidaps.events.EventPumpStatusChanged;
import info.nightscout.androidaps.interfaces.ProfileInterface; import info.nightscout.androidaps.interfaces.ProfileInterface;
import info.nightscout.androidaps.plugins.CircadianPercentageProfile.CircadianPercentageProfilePlugin; import info.nightscout.androidaps.plugins.CircadianPercentageProfile.CircadianPercentageProfilePlugin;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.DanaR.comm.RecordTypes; import info.nightscout.androidaps.plugins.DanaR.comm.RecordTypes;
import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRConnectionStatus;
import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRSyncStatus; import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRSyncStatus;
import info.nightscout.androidaps.plugins.DanaRKorean.Services.ExecutionService; import info.nightscout.androidaps.plugins.DanaRKorean.Services.ExecutionService;
import info.nightscout.utils.DecimalFormatter; import info.nightscout.utils.DecimalFormatter;
@ -68,11 +68,11 @@ public class DanaRStatsActivity extends Activity {
private Handler mHandler; private Handler mHandler;
private static HandlerThread mHandlerThread; private static HandlerThread mHandlerThread;
TextView statusView, statsMessage,totalBaseBasal2; TextView statusView, statsMessage, totalBaseBasal2;
EditText totalBaseBasal; EditText totalBaseBasal;
Button reloadButton; Button reloadButton;
LinearLayoutManager llm; LinearLayoutManager llm;
TableLayout tl,ctl,etl; TableLayout tl, ctl, etl;
String TBB; String TBB;
double magicNumber; double magicNumber;
DecimalFormat decimalFormat; DecimalFormat decimalFormat;
@ -118,15 +118,15 @@ public class DanaRStatsActivity extends Activity {
public boolean dispatchTouchEvent(MotionEvent event) { public boolean dispatchTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) { if (event.getAction() == MotionEvent.ACTION_DOWN) {
View myView = getCurrentFocus(); View myView = getCurrentFocus();
if ( myView instanceof EditText) { if (myView instanceof EditText) {
Rect rect = new Rect(); Rect rect = new Rect();
myView.getGlobalVisibleRect(rect); myView.getGlobalVisibleRect(rect);
if (!rect.contains((int)event.getRawX(), (int)event.getRawY())) { if (!rect.contains((int) event.getRawX(), (int) event.getRawY())) {
myView.clearFocus(); myView.clearFocus();
} }
} }
} }
return super.dispatchTouchEvent( event ); return super.dispatchTouchEvent(event);
} }
ServiceConnection mConnection = new ServiceConnection() { ServiceConnection mConnection = new ServiceConnection() {
@ -172,11 +172,11 @@ public class DanaRStatsActivity extends Activity {
totalBaseBasal.setText(TBB); totalBaseBasal.setText(TBB);
ProfileInterface pi = ConfigBuilderPlugin.getActiveProfile(); ProfileInterface pi = ConfigBuilderPlugin.getActiveProfile();
if (pi != null && pi instanceof CircadianPercentageProfilePlugin){ if (pi != null && pi instanceof CircadianPercentageProfilePlugin) {
double cppTBB = ((CircadianPercentageProfilePlugin)pi).baseBasalSum(); double cppTBB = ((CircadianPercentageProfilePlugin) pi).baseBasalSum();
totalBaseBasal.setText(decimalFormat.format(cppTBB)); totalBaseBasal.setText(decimalFormat.format(cppTBB));
SharedPreferences.Editor edit = preferences.edit(); SharedPreferences.Editor edit = preferences.edit();
edit.putString("TBB",totalBaseBasal.getText().toString()); edit.putString("TBB", totalBaseBasal.getText().toString());
edit.commit(); edit.commit();
TBB = preferences.getString("TBB", ""); TBB = preferences.getString("TBB", "");
} }
@ -312,7 +312,7 @@ public class DanaRStatsActivity extends Activity {
totalBaseBasal.setOnEditorActionListener(new TextView.OnEditorActionListener() { totalBaseBasal.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override @Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if(actionId== EditorInfo.IME_ACTION_DONE){ if (actionId == EditorInfo.IME_ACTION_DONE) {
totalBaseBasal.clearFocus(); totalBaseBasal.clearFocus();
return true; return true;
} }
@ -323,11 +323,11 @@ public class DanaRStatsActivity extends Activity {
totalBaseBasal.setOnFocusChangeListener(new View.OnFocusChangeListener() { totalBaseBasal.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override @Override
public void onFocusChange(View v, boolean hasFocus) { public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){ if (hasFocus) {
totalBaseBasal.getText().clear(); totalBaseBasal.getText().clear();
} else { } else {
SharedPreferences.Editor edit = preferences.edit(); SharedPreferences.Editor edit = preferences.edit();
edit.putString("TBB",totalBaseBasal.getText().toString()); edit.putString("TBB", totalBaseBasal.getText().toString());
edit.commit(); edit.commit();
TBB = preferences.getString("TBB", ""); TBB = preferences.getString("TBB", "");
loadDataFromDB(RecordTypes.RECORD_TYPE_DAILY); loadDataFromDB(RecordTypes.RECORD_TYPE_DAILY);
@ -362,15 +362,14 @@ public class DanaRStatsActivity extends Activity {
cleanTable(etl); cleanTable(etl);
DateFormat df = new SimpleDateFormat("dd.MM."); DateFormat df = new SimpleDateFormat("dd.MM.");
if(TextUtils.isEmpty(TBB)) { if (TextUtils.isEmpty(TBB)) {
totalBaseBasal.setError("Please Enter Total Base Basal"); totalBaseBasal.setError("Please Enter Total Base Basal");
return; return;
} } else {
else {
magicNumber = SafeParse.stringToDouble(TBB); magicNumber = SafeParse.stringToDouble(TBB);
} }
magicNumber *=2; magicNumber *= 2;
totalBaseBasal2.setText(decimalFormat.format(magicNumber)); totalBaseBasal2.setText(decimalFormat.format(magicNumber));
int i = 0; int i = 0;
@ -379,45 +378,45 @@ public class DanaRStatsActivity extends Activity {
double weighted05 = 0d; double weighted05 = 0d;
double weighted07 = 0d; double weighted07 = 0d;
for (DanaRHistoryRecord record: historyList) { for (DanaRHistoryRecord record : historyList) {
double tdd= record.getRecordDailyBolus() + record.getRecordDailyBasal(); double tdd = record.getRecordDailyBolus() + record.getRecordDailyBasal();
// Create the table row // Create the table row
TableRow tr = new TableRow(DanaRStatsActivity.this); TableRow tr = new TableRow(DanaRStatsActivity.this);
if(i%2!=0) tr.setBackgroundColor(Color.DKGRAY); if (i % 2 != 0) tr.setBackgroundColor(Color.DKGRAY);
tr.setId(100+i); tr.setId(100 + i);
tr.setLayoutParams(new TableLayout.LayoutParams( tr.setLayoutParams(new TableLayout.LayoutParams(
TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.MATCH_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT)); TableLayout.LayoutParams.WRAP_CONTENT));
// Here create the TextView dynamically // Here create the TextView dynamically
TextView labelDATE = new TextView(DanaRStatsActivity.this); TextView labelDATE = new TextView(DanaRStatsActivity.this);
labelDATE.setId(200+i); labelDATE.setId(200 + i);
labelDATE.setText(df.format(new Date(record.getRecordDate()))); labelDATE.setText(df.format(new Date(record.getRecordDate())));
labelDATE.setTextColor(Color.WHITE); labelDATE.setTextColor(Color.WHITE);
tr.addView(labelDATE); tr.addView(labelDATE);
TextView labelBASAL = new TextView(DanaRStatsActivity.this); TextView labelBASAL = new TextView(DanaRStatsActivity.this);
labelBASAL.setId(300+i); labelBASAL.setId(300 + i);
labelBASAL.setText(DecimalFormatter.to2Decimal(record.getRecordDailyBasal()) + " U"); labelBASAL.setText(DecimalFormatter.to2Decimal(record.getRecordDailyBasal()) + " U");
labelBASAL.setTextColor(Color.WHITE); labelBASAL.setTextColor(Color.WHITE);
tr.addView(labelBASAL); tr.addView(labelBASAL);
TextView labelBOLUS = new TextView(DanaRStatsActivity.this); TextView labelBOLUS = new TextView(DanaRStatsActivity.this);
labelBOLUS.setId(400+i); labelBOLUS.setId(400 + i);
labelBOLUS.setText(DecimalFormatter.to2Decimal(record.getRecordDailyBolus()) + " U"); labelBOLUS.setText(DecimalFormatter.to2Decimal(record.getRecordDailyBolus()) + " U");
labelBOLUS.setTextColor(Color.WHITE); labelBOLUS.setTextColor(Color.WHITE);
tr.addView(labelBOLUS); tr.addView(labelBOLUS);
TextView labelTDD = new TextView(DanaRStatsActivity.this); TextView labelTDD = new TextView(DanaRStatsActivity.this);
labelTDD.setId(500+i); labelTDD.setId(500 + i);
labelTDD.setText(DecimalFormatter.to2Decimal(tdd) + " U"); labelTDD.setText(DecimalFormatter.to2Decimal(tdd) + " U");
labelTDD.setTextColor(Color.WHITE); labelTDD.setTextColor(Color.WHITE);
tr.addView(labelTDD); tr.addView(labelTDD);
TextView labelRATIO = new TextView(DanaRStatsActivity.this); TextView labelRATIO = new TextView(DanaRStatsActivity.this);
labelRATIO.setId(600+i); labelRATIO.setId(600 + i);
labelRATIO.setText(Math.round(100*tdd/magicNumber) +" %"); labelRATIO.setText(Math.round(100 * tdd / magicNumber) + " %");
labelRATIO.setTextColor(Color.WHITE); labelRATIO.setTextColor(Color.WHITE);
tr.addView(labelRATIO); tr.addView(labelRATIO);
@ -431,28 +430,28 @@ public class DanaRStatsActivity extends Activity {
// Create the cumtable row // Create the cumtable row
TableRow ctr = new TableRow(DanaRStatsActivity.this); TableRow ctr = new TableRow(DanaRStatsActivity.this);
if(i%2==0) ctr.setBackgroundColor(Color.DKGRAY); if (i % 2 == 0) ctr.setBackgroundColor(Color.DKGRAY);
ctr.setId(700+i); ctr.setId(700 + i);
ctr.setLayoutParams(new TableLayout.LayoutParams( ctr.setLayoutParams(new TableLayout.LayoutParams(
TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.MATCH_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT)); TableLayout.LayoutParams.WRAP_CONTENT));
// Here create the TextView dynamically // Here create the TextView dynamically
TextView labelDAYS = new TextView(DanaRStatsActivity.this); TextView labelDAYS = new TextView(DanaRStatsActivity.this);
labelDAYS.setId(800+i); labelDAYS.setId(800 + i);
labelDAYS.setText("" + i); labelDAYS.setText("" + i);
labelDAYS.setTextColor(Color.WHITE); labelDAYS.setTextColor(Color.WHITE);
ctr.addView(labelDAYS); ctr.addView(labelDAYS);
TextView labelCUMTDD = new TextView(DanaRStatsActivity.this); TextView labelCUMTDD = new TextView(DanaRStatsActivity.this);
labelCUMTDD.setId(900+i); labelCUMTDD.setId(900 + i);
labelCUMTDD.setText(DecimalFormatter.to2Decimal(sum/i) + " U"); labelCUMTDD.setText(DecimalFormatter.to2Decimal(sum / i) + " U");
labelCUMTDD.setTextColor(Color.WHITE); labelCUMTDD.setTextColor(Color.WHITE);
ctr.addView(labelCUMTDD); ctr.addView(labelCUMTDD);
TextView labelCUMRATIO = new TextView(DanaRStatsActivity.this); TextView labelCUMRATIO = new TextView(DanaRStatsActivity.this);
labelCUMRATIO.setId(1000+i); labelCUMRATIO.setId(1000 + i);
labelCUMRATIO.setText(Math.round(100*sum/i/magicNumber) + " %"); labelCUMRATIO.setText(Math.round(100 * sum / i / magicNumber) + " %");
labelCUMRATIO.setTextColor(Color.WHITE); labelCUMRATIO.setTextColor(Color.WHITE);
ctr.addView(labelCUMRATIO); ctr.addView(labelCUMRATIO);
@ -462,7 +461,7 @@ public class DanaRStatsActivity extends Activity {
TableLayout.LayoutParams.WRAP_CONTENT)); TableLayout.LayoutParams.WRAP_CONTENT));
} }
if (historyList.size()<3 || !(df.format(new Date(historyList.get(0).getRecordDate())).equals(df.format(new Date(System.currentTimeMillis() - 1000*60*60*24))))){ if (historyList.size() < 3 || !(df.format(new Date(historyList.get(0).getRecordDate())).equals(df.format(new Date(System.currentTimeMillis() - 1000 * 60 * 60 * 24))))) {
statsMessage.setVisibility(View.VISIBLE); statsMessage.setVisibility(View.VISIBLE);
statsMessage.setText(getString(R.string.danar_stats_olddata_Message)); statsMessage.setText(getString(R.string.danar_stats_olddata_Message));
@ -474,38 +473,38 @@ public class DanaRStatsActivity extends Activity {
i = 0; i = 0;
for (DanaRHistoryRecord record: historyList) { for (DanaRHistoryRecord record : historyList) {
double tdd= record.getRecordDailyBolus() + record.getRecordDailyBasal(); double tdd = record.getRecordDailyBolus() + record.getRecordDailyBasal();
if(i == 0 ) { if (i == 0) {
weighted03 = tdd; weighted03 = tdd;
weighted05 = tdd; weighted05 = tdd;
weighted07 = tdd; weighted07 = tdd;
} else { } else {
weighted07 = (weighted07*0.3 + tdd*0.7); weighted07 = (weighted07 * 0.3 + tdd * 0.7);
weighted05 = (weighted05*0.5 + tdd*0.5); weighted05 = (weighted05 * 0.5 + tdd * 0.5);
weighted03 = (weighted03*0.7 + tdd*0.3); weighted03 = (weighted03 * 0.7 + tdd * 0.3);
} }
i++; i++;
} }
// Create the exptable row // Create the exptable row
TableRow etr = new TableRow(DanaRStatsActivity.this); TableRow etr = new TableRow(DanaRStatsActivity.this);
if(i%2!=0) etr.setBackgroundColor(Color.DKGRAY); if (i % 2 != 0) etr.setBackgroundColor(Color.DKGRAY);
etr.setId(1100+i); etr.setId(1100 + i);
etr.setLayoutParams(new TableLayout.LayoutParams( etr.setLayoutParams(new TableLayout.LayoutParams(
TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.MATCH_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT)); TableLayout.LayoutParams.WRAP_CONTENT));
// Here create the TextView dynamically // Here create the TextView dynamically
TextView labelWEIGHT = new TextView(DanaRStatsActivity.this); TextView labelWEIGHT = new TextView(DanaRStatsActivity.this);
labelWEIGHT.setId(1200+i); labelWEIGHT.setId(1200 + i);
labelWEIGHT.setText("0.3\n" + "0.5\n" + "0.7"); labelWEIGHT.setText("0.3\n" + "0.5\n" + "0.7");
labelWEIGHT.setTextColor(Color.WHITE); labelWEIGHT.setTextColor(Color.WHITE);
etr.addView(labelWEIGHT); etr.addView(labelWEIGHT);
TextView labelEXPTDD = new TextView(DanaRStatsActivity.this); TextView labelEXPTDD = new TextView(DanaRStatsActivity.this);
labelEXPTDD.setId(1300+i); labelEXPTDD.setId(1300 + i);
labelEXPTDD.setText(DecimalFormatter.to2Decimal(weighted03) labelEXPTDD.setText(DecimalFormatter.to2Decimal(weighted03)
+ " U\n" + DecimalFormatter.to2Decimal(weighted05) + " U\n" + DecimalFormatter.to2Decimal(weighted05)
+ " U\n" + DecimalFormatter.to2Decimal(weighted07) + " U"); + " U\n" + DecimalFormatter.to2Decimal(weighted07) + " U");
@ -513,10 +512,10 @@ public class DanaRStatsActivity extends Activity {
etr.addView(labelEXPTDD); etr.addView(labelEXPTDD);
TextView labelEXPRATIO = new TextView(DanaRStatsActivity.this); TextView labelEXPRATIO = new TextView(DanaRStatsActivity.this);
labelEXPRATIO.setId(1400+i); labelEXPRATIO.setId(1400 + i);
labelEXPRATIO.setText(Math.round(100*weighted03/magicNumber) +" %\n" labelEXPRATIO.setText(Math.round(100 * weighted03 / magicNumber) + " %\n"
+ Math.round(100*weighted05/magicNumber) +" %\n" + Math.round(100 * weighted05 / magicNumber) + " %\n"
+ Math.round(100*weighted07/magicNumber) +" %"); + Math.round(100 * weighted07 / magicNumber) + " %");
labelEXPRATIO.setTextColor(Color.WHITE); labelEXPRATIO.setTextColor(Color.WHITE);
etr.addView(labelEXPRATIO); etr.addView(labelEXPRATIO);
@ -549,21 +548,12 @@ public class DanaRStatsActivity extends Activity {
} }
@Subscribe @Subscribe
public void onStatusEvent(final EventDanaRConnectionStatus c) { public void onStatusEvent(final EventPumpStatusChanged c) {
runOnUiThread( runOnUiThread(
new Runnable() { new Runnable() {
@Override @Override
public void run() { public void run() {
if (c.sStatus == EventDanaRConnectionStatus.CONNECTING) { statusView.setText(c.textStatus());
statusView.setText(String.format(getString(R.string.danar_history_connectingfor), c.sSecondsElapsed));
log.debug("EventDanaRConnectionStatus: " + "Connecting for " + c.sSecondsElapsed + "s");
} else if (c.sStatus == EventDanaRConnectionStatus.CONNECTED) {
statusView.setText(MainApp.sResources.getString(R.string.connected));
log.debug("EventDanaRConnectionStatus: Connected");
} else {
statusView.setText(MainApp.sResources.getString(R.string.disconnected));
log.debug("EventDanaRConnectionStatus: Disconnected");
}
} }
} }
); );

View file

@ -8,11 +8,9 @@ import android.content.BroadcastReceiver;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.IntentFilter; import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Binder; import android.os.Binder;
import android.os.IBinder; import android.os.IBinder;
import android.os.PowerManager; import android.os.PowerManager;
import android.preference.PreferenceManager;
import com.squareup.otto.Subscribe; import com.squareup.otto.Subscribe;
@ -33,6 +31,7 @@ import info.nightscout.androidaps.db.Treatment;
import info.nightscout.androidaps.events.EventAppExit; import info.nightscout.androidaps.events.EventAppExit;
import info.nightscout.androidaps.events.EventInitializationChanged; import info.nightscout.androidaps.events.EventInitializationChanged;
import info.nightscout.androidaps.events.EventPreferenceChange; import info.nightscout.androidaps.events.EventPreferenceChange;
import info.nightscout.androidaps.events.EventPumpStatusChanged;
import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.plugins.DanaR.comm.MessageBase; import info.nightscout.androidaps.plugins.DanaR.comm.MessageBase;
import info.nightscout.androidaps.plugins.DanaR.comm.MsgBolusProgress; import info.nightscout.androidaps.plugins.DanaR.comm.MsgBolusProgress;
@ -59,7 +58,6 @@ import info.nightscout.androidaps.plugins.DanaR.comm.MsgSetTempBasalStop;
import info.nightscout.androidaps.plugins.DanaR.comm.MsgSetTime; import info.nightscout.androidaps.plugins.DanaR.comm.MsgSetTime;
import info.nightscout.androidaps.plugins.DanaR.comm.RecordTypes; import info.nightscout.androidaps.plugins.DanaR.comm.RecordTypes;
import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRBolusStart; import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRBolusStart;
import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRConnectionStatus;
import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRNewStatus; import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRNewStatus;
import info.nightscout.androidaps.plugins.DanaRKorean.DanaRKoreanPlugin; import info.nightscout.androidaps.plugins.DanaRKorean.DanaRKoreanPlugin;
import info.nightscout.androidaps.plugins.DanaRKorean.DanaRKoreanPump; import info.nightscout.androidaps.plugins.DanaRKorean.DanaRKoreanPump;
@ -75,16 +73,15 @@ import info.nightscout.androidaps.plugins.DanaRKorean.comm.MsgSettingShippingInf
import info.nightscout.androidaps.plugins.DanaRKorean.comm.MsgStatusBasic; import info.nightscout.androidaps.plugins.DanaRKorean.comm.MsgStatusBasic;
import info.nightscout.androidaps.plugins.DanaRKorean.comm.MsgStatusBolusExtended; import info.nightscout.androidaps.plugins.DanaRKorean.comm.MsgStatusBolusExtended;
import info.nightscout.androidaps.plugins.DanaRKorean.comm.MsgStatusTempBasal; import info.nightscout.androidaps.plugins.DanaRKorean.comm.MsgStatusTempBasal;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.androidaps.plugins.Overview.Notification; import info.nightscout.androidaps.plugins.Overview.Notification;
import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification; import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification;
import info.nightscout.client.data.NSProfile; import info.nightscout.utils.SP;
import info.nightscout.utils.SafeParse;
import info.nightscout.utils.ToastUtils; import info.nightscout.utils.ToastUtils;
public class ExecutionService extends Service { public class ExecutionService extends Service {
private static Logger log = LoggerFactory.getLogger(ExecutionService.class); private static Logger log = LoggerFactory.getLogger(ExecutionService.class);
private SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext());
private String devName; private String devName;
private SerialIOThread mSerialIOThread; private SerialIOThread mSerialIOThread;
@ -113,7 +110,7 @@ public class ExecutionService extends Service {
if (mSerialIOThread != null) { if (mSerialIOThread != null) {
mSerialIOThread.disconnect("BT disconnection broadcast"); mSerialIOThread.disconnect("BT disconnection broadcast");
} }
MainApp.bus().post(new EventDanaRConnectionStatus(EventDanaRConnectionStatus.DISCONNECTED, 0)); MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTED));
} }
} }
} }
@ -183,7 +180,7 @@ public class ExecutionService extends Service {
} }
public void connect(String from) { public void connect(String from) {
if (danaRKoreanPump.password != -1 && danaRKoreanPump.password != SafeParse.stringToInt(SP.getString("danar_password", "-1"))) { if (danaRKoreanPump.password != -1 && danaRKoreanPump.password != SP.getInt(R.string.key_danar_password, -1)) {
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.sResources.getString(R.string.wrongpumppassword), R.raw.error); ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.sResources.getString(R.string.wrongpumppassword), R.raw.error);
return; return;
} }
@ -203,7 +200,7 @@ public class ExecutionService extends Service {
long startTime = new Date().getTime(); long startTime = new Date().getTime();
while (!isConnected() && startTime + maxConnectionTime >= new Date().getTime()) { while (!isConnected() && startTime + maxConnectionTime >= new Date().getTime()) {
long secondsElapsed = (new Date().getTime() - startTime) / 1000L; long secondsElapsed = (new Date().getTime() - startTime) / 1000L;
MainApp.bus().post(new EventDanaRConnectionStatus(EventDanaRConnectionStatus.CONNECTING, (int) secondsElapsed)); MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.CONNECTING, (int) secondsElapsed));
if (Config.logDanaBTComm) if (Config.logDanaBTComm)
log.debug("connect waiting " + secondsElapsed + "sec from: " + from); log.debug("connect waiting " + secondsElapsed + "sec from: " + from);
try { try {
@ -222,18 +219,19 @@ public class ExecutionService extends Service {
mSerialIOThread.disconnect("Recreate SerialIOThread"); mSerialIOThread.disconnect("Recreate SerialIOThread");
} }
mSerialIOThread = new SerialIOThread(mRfcommSocket); mSerialIOThread = new SerialIOThread(mRfcommSocket);
MainApp.bus().post(new EventDanaRConnectionStatus(EventDanaRConnectionStatus.CONNECTED, 0)); MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.CONNECTED));
if (!getPumpStatus()) { if (!getPumpStatus()) {
mSerialIOThread.disconnect("getPumpStatus failed"); mSerialIOThread.disconnect("getPumpStatus failed");
waitMsec(3000); waitMsec(3000);
if (!MainApp.getSpecificPlugin(DanaRKoreanPlugin.class).isEnabled(PluginBase.PUMP)) if (!MainApp.getSpecificPlugin(DanaRKoreanPlugin.class).isEnabled(PluginBase.PUMP))
return; return;
getBTSocketForSelectedPump(); getBTSocketForSelectedPump();
startTime = new Date().getTime();
} }
} }
} }
if (!isConnected()) { if (!isConnected()) {
MainApp.bus().post(new EventDanaRConnectionStatus(EventDanaRConnectionStatus.DISCONNECTED, 0)); MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTED));
log.error("Pump connection timed out"); log.error("Pump connection timed out");
} }
connectionInProgress = false; connectionInProgress = false;
@ -242,7 +240,7 @@ public class ExecutionService extends Service {
} }
private void getBTSocketForSelectedPump() { private void getBTSocketForSelectedPump() {
devName = SP.getString("danar_bt_name", ""); devName = SP.getString(MainApp.sResources.getString(R.string.key_danar_bt_name), "");
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter != null) { if (bluetoothAdapter != null) {
@ -275,7 +273,7 @@ public class ExecutionService extends Service {
private boolean getPumpStatus() { private boolean getPumpStatus() {
try { try {
MainApp.bus().post(new EventDanaRConnectionStatus(EventDanaRConnectionStatus.PERFORMING, 0, MainApp.sResources.getString(R.string.gettingpumpstatus))); MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.gettingpumpstatus)));
//MsgStatus statusMsg = new MsgStatus(); //MsgStatus statusMsg = new MsgStatus();
MsgStatusBasic statusBasicMsg = new MsgStatusBasic(); MsgStatusBasic statusBasicMsg = new MsgStatusBasic();
MsgStatusTempBasal tempStatusMsg = new MsgStatusTempBasal(); MsgStatusTempBasal tempStatusMsg = new MsgStatusTempBasal();
@ -334,7 +332,7 @@ public class ExecutionService extends Service {
danaRKoreanPump.lastConnection = now; danaRKoreanPump.lastConnection = now;
MainApp.bus().post(new EventDanaRNewStatus()); MainApp.bus().post(new EventDanaRNewStatus());
MainApp.bus().post(new EventInitializationChanged()); MainApp.bus().post(new EventInitializationChanged());
MainApp.getConfigBuilder().uploadDeviceStatus(60); MainApp.getConfigBuilder().uploadDeviceStatus(15);
if (danaRKoreanPump.dailyTotalUnits > danaRKoreanPump.maxDailyTotalUnits * Constants.dailyLimitWarning ) { if (danaRKoreanPump.dailyTotalUnits > danaRKoreanPump.maxDailyTotalUnits * Constants.dailyLimitWarning ) {
log.debug("Approaching daily limit: " + danaRKoreanPump.dailyTotalUnits + "/" + danaRKoreanPump.maxDailyTotalUnits); log.debug("Approaching daily limit: " + danaRKoreanPump.dailyTotalUnits + "/" + danaRKoreanPump.maxDailyTotalUnits);
Notification reportFail = new Notification(Notification.APPROACHING_DAILY_LIMIT, MainApp.sResources.getString(R.string.approachingdailylimit), Notification.URGENT); Notification reportFail = new Notification(Notification.APPROACHING_DAILY_LIMIT, MainApp.sResources.getString(R.string.approachingdailylimit), Notification.URGENT);
@ -350,47 +348,46 @@ public class ExecutionService extends Service {
public boolean tempBasal(int percent, int durationInHours) { public boolean tempBasal(int percent, int durationInHours) {
connect("tempBasal"); connect("tempBasal");
if (!isConnected()) return false; if (!isConnected()) return false;
MainApp.bus().post(new EventDanaRConnectionStatus(EventDanaRConnectionStatus.PERFORMING, 0, MainApp.sResources.getString(R.string.settingtempbasal))); MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.settingtempbasal)));
mSerialIOThread.sendMessage(new MsgSetTempBasalStart(percent, durationInHours)); mSerialIOThread.sendMessage(new MsgSetTempBasalStart(percent, durationInHours));
mSerialIOThread.sendMessage(new MsgStatusTempBasal()); mSerialIOThread.sendMessage(new MsgStatusTempBasal());
MainApp.bus().post(new EventDanaRConnectionStatus(EventDanaRConnectionStatus.PERFORMING, 0, MainApp.sResources.getString(R.string.disconnecting))); MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING));
return true; return true;
} }
public boolean tempBasalStop() { public boolean tempBasalStop() {
connect("tempBasalStop"); connect("tempBasalStop");
if (!isConnected()) return false; if (!isConnected()) return false;
MainApp.bus().post(new EventDanaRConnectionStatus(EventDanaRConnectionStatus.PERFORMING, 0, MainApp.sResources.getString(R.string.stoppingtempbasal))); MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.stoppingtempbasal)));
mSerialIOThread.sendMessage(new MsgSetTempBasalStop()); mSerialIOThread.sendMessage(new MsgSetTempBasalStop());
mSerialIOThread.sendMessage(new MsgStatusTempBasal()); mSerialIOThread.sendMessage(new MsgStatusTempBasal());
MainApp.bus().post(new EventDanaRConnectionStatus(EventDanaRConnectionStatus.PERFORMING, 0, MainApp.sResources.getString(R.string.disconnecting))); MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING));
return true; return true;
} }
public boolean extendedBolus(double insulin, int durationInHalfHours) { public boolean extendedBolus(double insulin, int durationInHalfHours) {
connect("extendedBolus"); connect("extendedBolus");
if (!isConnected()) return false; if (!isConnected()) return false;
MainApp.bus().post(new EventDanaRConnectionStatus(EventDanaRConnectionStatus.PERFORMING, 0, MainApp.sResources.getString(R.string.settingextendedbolus))); MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.settingextendedbolus)));
mSerialIOThread.sendMessage(new MsgSetExtendedBolusStart(insulin, (byte) (durationInHalfHours & 0xFF))); mSerialIOThread.sendMessage(new MsgSetExtendedBolusStart(insulin, (byte) (durationInHalfHours & 0xFF)));
mSerialIOThread.sendMessage(new MsgStatusBolusExtended()); mSerialIOThread.sendMessage(new MsgStatusBolusExtended());
MainApp.bus().post(new EventDanaRConnectionStatus(EventDanaRConnectionStatus.PERFORMING, 0, MainApp.sResources.getString(R.string.disconnecting))); MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING));
return true; return true;
} }
public boolean extendedBolusStop() { public boolean extendedBolusStop() {
connect("extendedBolusStop"); connect("extendedBolusStop");
if (!isConnected()) return false; if (!isConnected()) return false;
MainApp.bus().post(new EventDanaRConnectionStatus(EventDanaRConnectionStatus.PERFORMING, 0, MainApp.sResources.getString(R.string.stoppingextendedbolus))); MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.stoppingextendedbolus)));
mSerialIOThread.sendMessage(new MsgSetExtendedBolusStop()); mSerialIOThread.sendMessage(new MsgSetExtendedBolusStop());
mSerialIOThread.sendMessage(new MsgStatusBolusExtended()); mSerialIOThread.sendMessage(new MsgStatusBolusExtended());
MainApp.bus().post(new EventDanaRConnectionStatus(EventDanaRConnectionStatus.PERFORMING, 0, MainApp.sResources.getString(R.string.disconnecting))); MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING));
return true; return true;
} }
public boolean bolus(Double amount, int carbs, Treatment t) { public boolean bolus(Double amount, int carbs, Treatment t) {
bolusingTreatment = t; bolusingTreatment = t;
MsgBolusStart start = new MsgBolusStart(amount); MsgBolusStart start = new MsgBolusStart(amount);
MsgBolusProgress progress = new MsgBolusProgress(amount, t); // initialize static variables
MsgBolusStop stop = new MsgBolusStop(amount, t); MsgBolusStop stop = new MsgBolusStop(amount, t);
connect("bolus"); connect("bolus");
@ -400,6 +397,8 @@ public class ExecutionService extends Service {
Calendar time = Calendar.getInstance(); Calendar time = Calendar.getInstance();
mSerialIOThread.sendMessage(new MsgSetCarbsEntry(time, carbs)); mSerialIOThread.sendMessage(new MsgSetCarbsEntry(time, carbs));
} }
MsgBolusProgress progress = new MsgBolusProgress(amount, t); // initialize static variables
MainApp.bus().post(new EventDanaRBolusStart()); MainApp.bus().post(new EventDanaRBolusStart());
if (!stop.stopped) { if (!stop.stopped) {
@ -410,7 +409,7 @@ public class ExecutionService extends Service {
} }
while (!stop.stopped && !start.failed) { while (!stop.stopped && !start.failed) {
waitMsec(100); waitMsec(100);
if (progress.lastReceive != 0 && (new Date().getTime() - progress.lastReceive) > 5 * 1000L) { // if i didn't receive status for more than 5 sec expecting broken comm if ((new Date().getTime() - progress.lastReceive) > 5 * 1000L) { // if i didn't receive status for more than 5 sec expecting broken comm
stop.stopped = true; stop.stopped = true;
stop.forced = true; stop.forced = true;
log.debug("Communication stopped"); log.debug("Communication stopped");
@ -495,13 +494,13 @@ public class ExecutionService extends Service {
public boolean updateBasalsInPump(final NSProfile profile) { public boolean updateBasalsInPump(final NSProfile profile) {
connect("updateBasalsInPump"); connect("updateBasalsInPump");
if (!isConnected()) return false; if (!isConnected()) return false;
MainApp.bus().post(new EventDanaRConnectionStatus(EventDanaRConnectionStatus.PERFORMING, 0, MainApp.sResources.getString(R.string.updatingbasalrates))); MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.updatingbasalrates)));
double[] basal = buildDanaRProfileRecord(profile); double[] basal = buildDanaRProfileRecord(profile);
MsgSetSingleBasalProfile msgSet = new MsgSetSingleBasalProfile(basal); MsgSetSingleBasalProfile msgSet = new MsgSetSingleBasalProfile(basal);
mSerialIOThread.sendMessage(msgSet); mSerialIOThread.sendMessage(msgSet);
danaRKoreanPump.lastSettingsRead = new Date(0); // force read full settings danaRKoreanPump.lastSettingsRead = new Date(0); // force read full settings
getPumpStatus(); getPumpStatus();
MainApp.bus().post(new EventDanaRConnectionStatus(EventDanaRConnectionStatus.PERFORMING, 0, MainApp.sResources.getString(R.string.disconnecting))); MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING));
return true; return true;
} }

View file

@ -15,8 +15,8 @@ import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.ProfileInterface; import info.nightscout.androidaps.interfaces.ProfileInterface;
import info.nightscout.androidaps.plugins.SimpleProfile.SimpleProfileFragment; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.client.data.NSProfile; import info.nightscout.utils.SP;
import info.nightscout.utils.SafeParse; import info.nightscout.utils.SafeParse;
/** /**
@ -63,7 +63,7 @@ public class LocalProfilePlugin implements PluginBase, ProfileInterface {
@Override @Override
public String getNameShort() { public String getNameShort() {
String name = MainApp.sResources.getString(R.string.localprofile_shortname); String name = MainApp.sResources.getString(R.string.localprofile_shortname);
if (!name.trim().isEmpty()){ if (!name.trim().isEmpty()) {
//only if translation exists //only if translation exists
return name; return name;
} }
@ -117,117 +117,48 @@ public class LocalProfilePlugin implements PluginBase, ProfileInterface {
private void loadSettings() { private void loadSettings() {
if (Config.logPrefsChange) if (Config.logPrefsChange)
log.debug("Loading stored settings"); log.debug("Loading stored settings");
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext());
if (settings.contains("LocalProfile" + "mgdl")) mgdl = SP.getBoolean("LocalProfile" + "mgdl", false);
mmol = SP.getBoolean("LocalProfile" + "mmol", true);
dia = SP.getDouble("LocalProfile" + "dia", 3d);
try { try {
mgdl = settings.getBoolean("LocalProfile" + "mgdl", false); ic = new JSONArray(SP.getString("LocalProfile" + "ic", DEFAULTARRAY));
} catch (Exception e) { } catch (JSONException e1) {
log.debug(e.getMessage());
}
else mgdl = false;
if (settings.contains("LocalProfile" + "mmol"))
try {
mmol = settings.getBoolean("LocalProfile" + "mmol", true);
} catch (Exception e) {
log.debug(e.getMessage());
}
else mmol = true;
if (settings.contains("LocalProfile" + "dia"))
try {
dia = SafeParse.stringToDouble(settings.getString("LocalProfile" + "dia", "3"));
} catch (Exception e) {
log.debug(e.getMessage());
}
else dia = 3d;
if (settings.contains("LocalProfile" + "ic"))
try {
ic = new JSONArray(settings.getString("LocalProfile" + "ic", DEFAULTARRAY));
} catch (Exception e) {
log.debug(e.getMessage());
try { try {
ic = new JSONArray(DEFAULTARRAY); ic = new JSONArray(DEFAULTARRAY);
} catch (JSONException e2) {
}
}
try {
isf = new JSONArray(SP.getString("LocalProfile" + "isf", DEFAULTARRAY));
} catch (JSONException e1) { } catch (JSONException e1) {
e1.printStackTrace();
}
}
else {
try {
ic = new JSONArray(DEFAULTARRAY);
} catch (JSONException e) {
e.printStackTrace();
}
}
if (settings.contains("LocalProfile" + "isf"))
try {
isf = new JSONArray(settings.getString("LocalProfile" + "isf", DEFAULTARRAY));
} catch (Exception e) {
log.debug(e.getMessage());
try { try {
isf = new JSONArray(DEFAULTARRAY); isf = new JSONArray(DEFAULTARRAY);
} catch (JSONException e2) {
}
}
try {
basal = new JSONArray(SP.getString("LocalProfile" + "basal", DEFAULTARRAY));
} catch (JSONException e1) { } catch (JSONException e1) {
e1.printStackTrace();
}
}
else {
try {
isf = new JSONArray(DEFAULTARRAY);
} catch (JSONException e) {
e.printStackTrace();
}
}
if (settings.contains("LocalProfile" + "basal"))
try {
basal = new JSONArray(settings.getString("LocalProfile" + "basal", DEFAULTARRAY));
} catch (Exception e) {
log.debug(e.getMessage());
try { try {
basal = new JSONArray(DEFAULTARRAY); basal = new JSONArray(DEFAULTARRAY);
} catch (JSONException e2) {
}
}
try {
targetLow = new JSONArray(SP.getString("LocalProfile" + "targetlow", DEFAULTARRAY));
} catch (JSONException e1) { } catch (JSONException e1) {
e1.printStackTrace();
}
}
else {
try {
basal = new JSONArray(DEFAULTARRAY);
} catch (JSONException e) {
e.printStackTrace();
}
}
if (settings.contains("LocalProfile" + "targetlow"))
try {
targetLow = new JSONArray(settings.getString("LocalProfile" + "targetlow", DEFAULTARRAY));
} catch (Exception e) {
log.debug(e.getMessage());
try { try {
targetLow = new JSONArray(DEFAULTARRAY); targetLow = new JSONArray(DEFAULTARRAY);
} catch (JSONException e2) {
}
}
try {
targetHigh = new JSONArray(SP.getString("LocalProfile" + "targethigh", DEFAULTARRAY));
} catch (JSONException e1) { } catch (JSONException e1) {
e1.printStackTrace();
}
}
else {
try {
targetLow = new JSONArray(DEFAULTARRAY);
} catch (JSONException e) {
e.printStackTrace();
}
}
if (settings.contains("LocalProfile" + "targethigh"))
try {
targetHigh = new JSONArray(settings.getString("LocalProfile" + "targethigh", DEFAULTARRAY));
} catch (Exception e) {
log.debug(e.getMessage());
try { try {
targetHigh = new JSONArray(DEFAULTARRAY); targetHigh = new JSONArray(DEFAULTARRAY);
} catch (JSONException e1) { } catch (JSONException e2) {
e1.printStackTrace();
}
}
else {
try {
targetHigh = new JSONArray(DEFAULTARRAY);
} catch (JSONException e) {
e.printStackTrace();
} }
} }
createConvertedProfile(); createConvertedProfile();

View file

@ -2,7 +2,6 @@ package info.nightscout.androidaps.plugins.Loop;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.os.Bundle; import android.os.Bundle;
import org.json.JSONException; import org.json.JSONException;
@ -10,12 +9,9 @@ import org.json.JSONObject;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.List;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.Services.Intents; import info.nightscout.androidaps.Services.Intents;
import info.nightscout.client.data.DbLogger; import info.nightscout.androidaps.plugins.NSClientInternal.data.DbLogger;
/* /*
{ {

View file

@ -228,7 +228,7 @@ public class LoopPlugin implements PluginBase {
} }
MainApp.bus().post(new EventLoopUpdateGui()); MainApp.bus().post(new EventLoopUpdateGui());
MainApp.getConfigBuilder().uploadDeviceStatus(120); MainApp.getConfigBuilder().uploadDeviceStatus(60);
} finally { } finally {
if (Config.logFunctionCalls) if (Config.logFunctionCalls)
log.debug("invoke end"); log.debug("invoke end");

View file

@ -7,7 +7,6 @@ import org.json.JSONObject;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.sql.SQLException;
import java.util.Date; import java.util.Date;
import info.nightscout.androidaps.BuildConfig; import info.nightscout.androidaps.BuildConfig;
@ -19,10 +18,7 @@ import info.nightscout.androidaps.db.TempBasal;
import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginBase;
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.Overview.events.EventOverviewBolusProgress; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.androidaps.plugins.VirtualPump.VirtualPumpFragment;
import info.nightscout.androidaps.plugins.VirtualPump.events.EventVirtualPumpUpdateGui;
import info.nightscout.client.data.NSProfile;
import info.nightscout.utils.DateUtil; import info.nightscout.utils.DateUtil;
/** /**
@ -147,12 +143,12 @@ public class MDIPlugin implements PluginBase, PumpInterface {
} }
@Override @Override
public Date lastStatusTime() { public Date lastDataTime() {
return new Date(); return new Date();
} }
@Override @Override
public void updateStatus(String reason) { public void refreshDataFromPump(String reason) {
// do nothing // do nothing
} }

View file

@ -0,0 +1,171 @@
package info.nightscout.androidaps.plugins.NSClientInternal;
import android.app.Activity;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Html;
import android.text.Spanned;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ScrollView;
import android.widget.TextView;
import com.squareup.otto.Subscribe;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.events.EventPreferenceChange;
import info.nightscout.androidaps.interfaces.FragmentBase;
import info.nightscout.androidaps.plugins.NSClientInternal.events.EventNSClientNewLog;
import info.nightscout.androidaps.plugins.NSClientInternal.events.EventNSClientRestart;
import info.nightscout.androidaps.plugins.NSClientInternal.events.EventNSClientUpdateGUI;
import info.nightscout.utils.SP;
public class NSClientInternalFragment extends Fragment implements FragmentBase, View.OnClickListener, CompoundButton.OnCheckedChangeListener {
private static Logger log = LoggerFactory.getLogger(NSClientInternalFragment.class);
static NSClientInternalPlugin nsClientInternalPlugin;
static public NSClientInternalPlugin getPlugin() {
if (nsClientInternalPlugin == null) {
nsClientInternalPlugin = new NSClientInternalPlugin();
}
return nsClientInternalPlugin;
}
private TextView logTextView;
private TextView queueTextView;
private TextView urlTextView;
private TextView statusTextView;
private TextView clearlog;
private TextView restart;
private TextView delivernow;
private TextView clearqueue;
private TextView showqueue;
private ScrollView logScrollview;
private CheckBox autoscrollCheckbox;
private CheckBox pausedCheckbox;
String status = "";
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.nsclientinternal_fragment, container, false);
logScrollview = (ScrollView) view.findViewById(R.id.nsclientinternal_logscrollview);
autoscrollCheckbox = (CheckBox) view.findViewById(R.id.nsclientinternal_autoscroll);
autoscrollCheckbox.setChecked(getPlugin().autoscroll);
autoscrollCheckbox.setOnCheckedChangeListener(this);
pausedCheckbox = (CheckBox) view.findViewById(R.id.nsclientinternal_paused);
pausedCheckbox.setChecked(getPlugin().paused);
pausedCheckbox.setOnCheckedChangeListener(this);
logTextView = (TextView) view.findViewById(R.id.nsclientinternal_log);
queueTextView = (TextView) view.findViewById(R.id.nsclientinternal_queue);
urlTextView = (TextView) view.findViewById(R.id.nsclientinternal_url);
statusTextView = (TextView) view.findViewById(R.id.nsclientinternal_status);
clearlog = (TextView) view.findViewById(R.id.nsclientinternal_clearlog);
clearlog.setOnClickListener(this);
clearlog.setPaintFlags(clearlog.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
restart = (TextView) view.findViewById(R.id.nsclientinternal_restart);
restart.setOnClickListener(this);
restart.setPaintFlags(restart.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
delivernow = (TextView) view.findViewById(R.id.nsclientinternal_delivernow);
delivernow.setOnClickListener(this);
delivernow.setPaintFlags(delivernow.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
clearqueue = (TextView) view.findViewById(R.id.nsclientinternal_clearqueue);
clearqueue.setOnClickListener(this);
clearqueue.setPaintFlags(clearqueue.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
showqueue = (TextView) view.findViewById(R.id.nsclientinternal_showqueue);
showqueue.setOnClickListener(this);
showqueue.setPaintFlags(showqueue.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
updateGUI();
return view;
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.nsclientinternal_restart:
MainApp.bus().post(new EventNSClientRestart());
break;
case R.id.nsclientinternal_delivernow:
getPlugin().resend("GUI");
break;
case R.id.nsclientinternal_clearlog:
getPlugin().clearLog();
break;
case R.id.nsclientinternal_clearqueue:
getPlugin().queue().reset();
break;
case R.id.nsclientinternal_showqueue:
MainApp.bus().post(new EventNSClientNewLog("QUEUE", getPlugin().queue().textList()));
break;
}
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
switch (buttonView.getId()) {
case R.id.nsclientinternal_paused:
SP.putBoolean(R.string.key_nsclientinternal_paused, isChecked);
getPlugin().paused = isChecked;
MainApp.bus().post(new EventPreferenceChange(R.string.key_nsclientinternal_paused));
updateGUI();
break;
case R.id.nsclientinternal_autoscroll:
SP.putBoolean(R.string.key_nsclientinternal_autoscroll, isChecked);
getPlugin().autoscroll = isChecked;
updateGUI();
break;
}
}
@Override
public void onPause() {
super.onPause();
MainApp.bus().unregister(this);
}
@Override
public void onResume() {
super.onResume();
MainApp.bus().register(this);
updateGUI();
}
@Subscribe
public void onStatusEvent(final EventNSClientUpdateGUI ev) {
updateGUI();
}
private void updateGUI() {
Activity activity = getActivity();
if (activity != null)
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
logTextView.setText(getPlugin().textLog);
if (getPlugin().autoscroll) {
logScrollview.fullScroll(ScrollView.FOCUS_DOWN);
}
urlTextView.setText(getPlugin().url());
Spanned queuetext = Html.fromHtml(MainApp.sResources.getString(R.string.queue) + " <b>" + getPlugin().queue().size() + "</b>");
queueTextView.setText(queuetext);
statusTextView.setText(getPlugin().status);
}
});
}
}

View file

@ -0,0 +1,217 @@
package info.nightscout.androidaps.plugins.NSClientInternal;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.text.Html;
import android.text.Spanned;
import android.text.TextUtils;
import com.squareup.otto.Subscribe;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.SimpleDateFormat;
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.events.EventAppExit;
import info.nightscout.androidaps.events.EventPreferenceChange;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PumpDescription;
import info.nightscout.androidaps.plugins.DanaR.Services.ExecutionService;
import info.nightscout.androidaps.plugins.NSClientInternal.events.EventNSClientNewLog;
import info.nightscout.androidaps.plugins.NSClientInternal.events.EventNSClientRestart;
import info.nightscout.androidaps.plugins.NSClientInternal.events.EventNSClientStatus;
import info.nightscout.androidaps.plugins.NSClientInternal.events.EventNSClientUpdateGUI;
import info.nightscout.androidaps.plugins.NSClientInternal.services.NSClientService;
import info.nightscout.utils.SP;
public class NSClientInternalPlugin implements PluginBase {
private static Logger log = LoggerFactory.getLogger(NSClientInternalPlugin.class);
boolean fragmentEnabled = false;
boolean fragmentVisible = false;
static public Handler handler;
static private HandlerThread handlerThread;
public List<EventNSClientNewLog> listLog = new ArrayList<EventNSClientNewLog>();
public Spanned textLog = Html.fromHtml("");
public boolean paused = false;
public boolean autoscroll = true;
public String status = "";
public NSClientService nsClientService = null;
public NSClientInternalPlugin() {
MainApp.bus().register(this);
paused = SP.getBoolean(R.string.key_nsclientinternal_paused, false);
autoscroll = SP.getBoolean(R.string.key_nsclientinternal_autoscroll, true);
if (handler == null) {
handlerThread = new HandlerThread(NSClientInternalPlugin.class.getSimpleName() + "Handler");
handlerThread.start();
handler = new Handler(handlerThread.getLooper());
}
Context context = MainApp.instance().getApplicationContext();
Intent intent = new Intent(context, NSClientService.class);
context.bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
@Override
public int getType() {
return PluginBase.GENERAL;
}
@Override
public String getFragmentClass() {
return NSClientInternalFragment.class.getName();
}
@Override
public String getName() {
return MainApp.sResources.getString(R.string.nsclientinternal);
}
@Override
public String getNameShort() {
String name = MainApp.sResources.getString(R.string.nsclientinternal_shortname);
if (!name.trim().isEmpty()) {
//only if translation exists
return name;
}
// use long name as fallback
return getName();
}
@Override
public boolean isEnabled(int type) {
return type == GENERAL && fragmentEnabled;
}
@Override
public boolean isVisibleInTabs(int type) {
return type == GENERAL && fragmentVisible;
}
@Override
public boolean canBeHidden(int type) {
return true;
}
@Override
public void setFragmentEnabled(int type, boolean fragmentEnabled) {
if (type == GENERAL) this.fragmentEnabled = fragmentEnabled;
}
@Override
public void setFragmentVisible(int type, boolean fragmentVisible) {
if (type == GENERAL) this.fragmentVisible = fragmentVisible;
}
ServiceConnection mConnection = new ServiceConnection() {
public void onServiceDisconnected(ComponentName name) {
log.debug("Service is disconnected");
nsClientService = null;
}
public void onServiceConnected(ComponentName name, IBinder service) {
log.debug("Service is connected");
NSClientService.LocalBinder mLocalBinder = (NSClientService.LocalBinder) service;
nsClientService = mLocalBinder.getServiceInstance();
}
};
@SuppressWarnings("UnusedParameters")
@Subscribe
public void onStatusEvent(final EventAppExit e) {
if (nsClientService != null)
MainApp.instance().getApplicationContext().unbindService(mConnection);
}
@Subscribe
public void onStatusEvent(final EventPreferenceChange s) {
//TODO
}
@Subscribe
public void onStatusEvent(final EventNSClientNewLog ev) {
addToLog(ev);
log.debug(ev.action + " " + ev.logText);
}
@Subscribe
public void onStatusEvent(final EventNSClientRestart ev) {
if (nsClientService != null)
nsClientService.restart();
}
@Subscribe
public void onStatusEvent(final EventNSClientStatus ev) {
status = ev.status;
MainApp.bus().post(new EventNSClientUpdateGUI());
}
public void clearLog() {
handler.post(new Runnable() {
@Override
public void run() {
listLog = new ArrayList<EventNSClientNewLog>();
updateLog();
}
});
}
private void addToLog(final EventNSClientNewLog ev) {
handler.post(new Runnable() {
@Override
public void run() {
SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
listLog.add(ev);
// remove the first line if log is too large
if (listLog.size() >= Constants.MAX_LOG_LINES) {
listLog.remove(0);
}
updateLog();
}
});
}
private void updateLog() {
Spanned newTextLog = Html.fromHtml("");
for (EventNSClientNewLog log : listLog) {
newTextLog = (Spanned) TextUtils.concat(newTextLog, log.toHtml());
}
textLog = newTextLog;
MainApp.bus().post(new EventNSClientUpdateGUI());
}
public void resend(String reason) {
if (nsClientService != null)
nsClientService.resend(reason);
}
public UploadQueue queue() {
return NSClientService.uploadQueue;
}
public String url() {
return NSClientService.nsURL;
}
}

View file

@ -0,0 +1,159 @@
package info.nightscout.androidaps.plugins.NSClientInternal;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.plugins.NSClientInternal.broadcasts.BroadcastQueueStatus;
import info.nightscout.androidaps.plugins.NSClientInternal.data.DbRequest;
import info.nightscout.androidaps.plugins.NSClientInternal.services.NSClientService;
import info.nightscout.utils.SP;
/**
* Created by mike on 21.02.2016.
*/
public class UploadQueue {
private static Logger log = LoggerFactory.getLogger(UploadQueue.class);
public static HashMap<String, DbRequest> queue = null;
public UploadQueue() {
loadMap();
}
public static String status() {
return "QUEUE: " + queue.size();
}
public static int size() {
return queue.size();
}
public static void add(final DbRequest dbr) {
NSClientService.handler.post(new Runnable() {
@Override
public void run() {
log.debug("QUEUE adding: " + dbr.data.toString());
queue.put(dbr.hash(), dbr);
saveMap();
}
});
}
public static void reset() {
NSClientService.handler.post(new Runnable() {
@Override
public void run() {
log.debug("QUEUE Reset");
queue.clear();
log.debug(status());
}
});
}
public static void removeID(final JSONObject record) {
NSClientService.handler.post(new Runnable() {
@Override
public void run() {
try {
long id = -1L;
if (record.has("NSCLIENT_ID")) {
id = record.getLong("NSCLIENT_ID");
} else {
return;
}
Iterator<Map.Entry<String, DbRequest>> iter = queue.entrySet().iterator();
while (iter.hasNext()) {
DbRequest dbr = iter.next().getValue();
JSONObject data = dbr.data;
long nsclientId = -1;
if (data.has("NSCLIENT_ID")) {
nsclientId = data.getLong("NSCLIENT_ID");
if (nsclientId == id) {
log.debug("Removing item from UploadQueue");
iter.remove();
log.debug(UploadQueue.status());
return;
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
saveMap();
}
});
}
public static void removeID(final String action, final String _id) {
NSClientService.handler.post(new Runnable() {
@Override
public void run() {
Iterator<Map.Entry<String, DbRequest>> iter = queue.entrySet().iterator();
while (iter.hasNext()) {
DbRequest dbr = iter.next().getValue();
if (dbr.action.equals(action) && dbr._id.equals(_id)) {
log.debug("Removing item from UploadQueue");
iter.remove();
return;
} else {
log.debug("Failed removing item from UploadQueue");
}
}
saveMap();
}
});
}
final static String KEY = "UploadQueue";
private static void saveMap() {
JSONArray jsonArray = new JSONArray();
Iterator<Map.Entry<String, DbRequest>> iter = queue.entrySet().iterator();
while (iter.hasNext()) {
DbRequest dbr = iter.next().getValue();
jsonArray.put(dbr.toJSON());
}
SP.putString(KEY, jsonArray.toString());
}
private void loadMap() {
queue = new HashMap<String, DbRequest>();
try {
String jsonString = SP.getString(KEY, (new JSONArray()).toString());
JSONArray jsonArray = new JSONArray(jsonString);
for (int i=0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
DbRequest dbr = DbRequest.fromJSON(jsonObject);
queue.put(dbr.hash(), dbr);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public String textList() {
Iterator<Map.Entry<String, DbRequest>> iter = queue.entrySet().iterator();
String result = "";
while (iter.hasNext()) {
DbRequest dbr = iter.next().getValue();
result += "<br>";
result += dbr.action.toUpperCase() + " ";
result += dbr.collection + ": ";
result += dbr.data.toString();
}
return result;
}
}

View file

@ -0,0 +1,55 @@
package info.nightscout.androidaps.plugins.NSClientInternal.acks;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.plugins.NSClientInternal.events.EventNSClientRestart;
import info.nightscout.androidaps.plugins.NSClientInternal.services.NSClientService;
import io.socket.client.Ack;
/**
* Created by mike on 29.12.2015.
*/
public class NSAddAck implements Ack {
private static Logger log = LoggerFactory.getLogger(NSAddAck.class);
public String _id = null;
public String nsClientID = null;
public JSONObject json = null;
public void call(Object...args) {
// Regular response
try {
JSONArray responsearray = (JSONArray) (args[0]);
JSONObject response = null;
if (responsearray.length()>0) {
response = responsearray.getJSONObject(0);
_id = response.getString("_id");
json = response;
if (response.has("NSCLIENT_ID")) {
nsClientID = response.getString("NSCLIENT_ID");
}
}
MainApp.bus().post(this);
return;
} catch (Exception e) {
}
// Check for not authorized
try {
JSONObject response = (JSONObject) (args[0]);
if (response.has("result")) {
_id = null;
if (response.getString("result").contains("Not")) {
MainApp.bus().post(new EventNSClientRestart());
return;
}
log.debug("DBACCESS " + response.getString("result"));
}
return;
} catch (Exception e) {
e.printStackTrace();
}
}
}

View file

@ -0,0 +1,24 @@
package info.nightscout.androidaps.plugins.NSClientInternal.acks;
import org.json.JSONObject;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.plugins.NSClientInternal.events.EventNSClientNewLog;
import io.socket.client.Ack;
/**
* Created by mike on 02.01.2016.
*/
public class NSAuthAck implements Ack{
public boolean read = false;
public boolean write = false;
public boolean write_treatment = false;
public void call(Object...args) {
JSONObject response = (JSONObject)args[0];
read = response.optBoolean("read");
write = response.optBoolean("write");
write_treatment = response.optBoolean("write_treatment");
MainApp.bus().post(this);
}
}

View file

@ -0,0 +1,38 @@
package info.nightscout.androidaps.plugins.NSClientInternal.acks;
import org.json.JSONException;
import org.json.JSONObject;
import io.socket.client.Ack;
/**
* Created by mike on 29.12.2015.
*/
public class NSPingAck implements Ack {
public long mills = 0;
public boolean received = false;
public boolean auth_received = false;
public boolean read = false;
public boolean write = false;
public boolean write_treatment = false;
public void call(Object...args) {
JSONObject response = (JSONObject)args[0];
mills = response.optLong("mills");
if (response.has("authorization")) {
auth_received = true;
try {
JSONObject authorization = response.getJSONObject("authorization");
read = authorization.optBoolean("read");
write = authorization.optBoolean("write");
write_treatment = authorization.optBoolean("write_treatment");
} catch (JSONException e) {
e.printStackTrace();
}
}
received = true;
synchronized(this) {
this.notify();
}
}
}

View file

@ -0,0 +1,39 @@
package info.nightscout.androidaps.plugins.NSClientInternal.acks;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.MainApp;
import io.socket.client.Ack;
/**
* Created by mike on 21.02.2016.
*/
public class NSUpdateAck implements Ack {
private static Logger log = LoggerFactory.getLogger(NSUpdateAck.class);
public boolean result = false;
public String _id = null;
public String action;
public void call(Object...args) {
JSONObject response = (JSONObject)args[0];
if (response.has("result"))
try {
if (response.getString("result").equals("success"))
result = true;
else if (response.getString("result").equals("Missing _id")) {
result = true;
log.debug("Internal error: Missing _id returned on dbUpdate ack");
}
MainApp.bus().post(this);
} catch (JSONException e) {
}
}
public NSUpdateAck(String action, String _id) {
super();
this.action = action;
this._id = _id;
}
}

View file

@ -0,0 +1,34 @@
package info.nightscout.androidaps.plugins.NSClientInternal.broadcasts;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import org.json.JSONArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import info.nightscout.androidaps.Services.Intents;
/**
* Created by mike on 26.06.2016.
*/
public class BroadcastCals {
private static Logger log = LoggerFactory.getLogger(BroadcastCals.class);
public void handleNewCal(JSONArray cals, Context context, boolean isDelta) {
Bundle bundle = new Bundle();
bundle.putString("cals", cals.toString());
bundle.putBoolean("delta", isDelta);
Intent intent = new Intent(Intents.ACTION_NEW_CAL);
intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
context.sendBroadcast(intent);
List<ResolveInfo> x = context.getPackageManager().queryBroadcastReceivers(intent, 0);
log.debug("CAL " + x.size() + " receivers");
}
}

View file

@ -0,0 +1,45 @@
package info.nightscout.androidaps.plugins.NSClientInternal.broadcasts;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import info.nightscout.androidaps.Services.Intents;
public class BroadcastDeviceStatus {
private static Logger log = LoggerFactory.getLogger(BroadcastDeviceStatus.class);
public void handleNewDeviceStatus(JSONObject status, Context context, boolean isDelta) {
Bundle bundle = new Bundle();
bundle.putString("devicestatus", status.toString());
bundle.putBoolean("delta", isDelta);
Intent intent = new Intent(Intents.ACTION_NEW_DEVICESTATUS);
intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
context.sendBroadcast(intent);
List<ResolveInfo> x = context.getPackageManager().queryBroadcastReceivers(intent, 0);
log.debug("DEVICESTATUS " + x.size() + " receivers");
}
public void handleNewDeviceStatus(JSONArray statuses, Context context, boolean isDelta) {
Bundle bundle = new Bundle();
bundle.putString("devicestatuses", statuses.toString());
bundle.putBoolean("delta", isDelta);
Intent intent = new Intent(Intents.ACTION_NEW_DEVICESTATUS);
intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
context.sendBroadcast(intent);
List<ResolveInfo> x = context.getPackageManager().queryBroadcastReceivers(intent, 0);
log.debug("DEVICESTATUS " + x.size() + " receivers");
}
}

View file

@ -0,0 +1,34 @@
package info.nightscout.androidaps.plugins.NSClientInternal.broadcasts;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import org.json.JSONArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import info.nightscout.androidaps.Services.Intents;
/**
* Created by mike on 26.06.2016.
*/
public class BroadcastMbgs {
private static Logger log = LoggerFactory.getLogger(BroadcastMbgs.class);
public void handleNewMbg(JSONArray mbgs, Context context, boolean isDelta) {
Bundle bundle = new Bundle();
bundle.putString("mbgs", mbgs.toString());
bundle.putBoolean("delta", isDelta);
Intent intent = new Intent(Intents.ACTION_NEW_MBG);
intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
context.sendBroadcast(intent);
List<ResolveInfo> x = context.getPackageManager().queryBroadcastReceivers(intent, 0);
log.debug("MBG " + x.size() + " receivers");
}
}

View file

@ -0,0 +1,37 @@
package info.nightscout.androidaps.plugins.NSClientInternal.broadcasts;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import info.nightscout.androidaps.Services.Intents;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
/**
* Created by mike on 20.02.2016.
*/
public class BroadcastProfile {
private static Logger log = LoggerFactory.getLogger(BroadcastProfile.class);
public void handleNewTreatment(NSProfile profile, Context context, boolean isDelta) {
Bundle bundle = new Bundle();
bundle.putString("profile", profile.getData().toString());
bundle.putString("activeprofile", profile.getActiveProfile());
bundle.putBoolean("delta", isDelta);
Intent intent = new Intent(Intents.ACTION_NEW_PROFILE);
intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
context.sendBroadcast(intent);
List<ResolveInfo> x = context.getPackageManager().queryBroadcastReceivers(intent, 0);
log.debug("PROFILE " + x.size() + " receivers");
}
}

View file

@ -0,0 +1,30 @@
package info.nightscout.androidaps.plugins.NSClientInternal.broadcasts;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.PowerManager;
import info.nightscout.androidaps.Services.Intents;
/**
* Created by mike on 28.02.2016.
*/
public class BroadcastQueueStatus {
public void handleNewStatus(int size, Context context) {
PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"sendQueue");
wakeLock.acquire();
try {
Bundle bundle = new Bundle();
bundle.putInt("size", size);
Intent intent = new Intent(Intents.ACTION_QUEUE_STATUS);
intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
context.sendBroadcast(intent);
} finally {
wakeLock.release();
}
}
}

View file

@ -0,0 +1,49 @@
package info.nightscout.androidaps.plugins.NSClientInternal.broadcasts;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import info.nightscout.androidaps.Services.Intents;
/**
* Created by mike on 22.02.2016.
*/
public class BroadcastSgvs {
private static Logger log = LoggerFactory.getLogger(BroadcastSgvs.class);
public void handleNewSgv(JSONObject sgv, Context context, boolean isDelta) {
Bundle bundle = new Bundle();
bundle.putString("sgv", sgv.toString());
bundle.putBoolean("delta", isDelta);
Intent intent = new Intent(Intents.ACTION_NEW_SGV);
intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
context.sendBroadcast(intent);
List<ResolveInfo> x = context.getPackageManager().queryBroadcastReceivers(intent, 0);
log.debug("SGV " + x.size() + " receivers");
}
public void handleNewSgv(JSONArray sgvs, Context context, boolean isDelta) {
Bundle bundle = new Bundle();
bundle.putString("sgvs", sgvs.toString());
bundle.putBoolean("delta", isDelta);
Intent intent = new Intent(Intents.ACTION_NEW_SGV);
intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
context.sendBroadcast(intent);
List<ResolveInfo> x = context.getPackageManager().queryBroadcastReceivers(intent, 0);
log.debug("SGV " + x.size() + " receivers");
}
}

View file

@ -0,0 +1,45 @@
package info.nightscout.androidaps.plugins.NSClientInternal.broadcasts;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.Services.Intents;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSStatus;
import info.nightscout.androidaps.plugins.NSClientInternal.services.NSClientService;
/**
* Created by mike on 24.02.2016.
*/
public class BroadcastStatus {
private static Logger log = LoggerFactory.getLogger(BroadcastStatus.class);
public void handleNewStatus(NSStatus status, Context context, boolean isDelta) {
Bundle bundle = new Bundle();
try {
bundle.putString("nsclientversionname", MainApp.instance().getPackageManager().getPackageInfo(MainApp.instance().getPackageName(), 0).versionName);
bundle.putInt("nsclientversioncode", MainApp.instance().getPackageManager().getPackageInfo(MainApp.instance().getPackageName(), 0).versionCode);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
};
bundle.putString("nightscoutversionname", NSClientService.nightscoutVersionName);
bundle.putInt("nightscoutversioncode", NSClientService.nightscoutVersionCode);
bundle.putString("status", status.getData().toString());
bundle.putBoolean("delta", isDelta);
Intent intent = new Intent(Intents.ACTION_NEW_STATUS);
intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
context.sendBroadcast(intent);
List<ResolveInfo> x = context.getPackageManager().queryBroadcastReceivers(intent, 0);
log.debug("STATUS: " + x.size() + " receivers");
}
}

View file

@ -0,0 +1,107 @@
package info.nightscout.androidaps.plugins.NSClientInternal.broadcasts;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ResolveInfo;
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 java.util.List;
import info.nightscout.androidaps.Services.Intents;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSTreatment;
/**
* Created by mike on 20.02.2016.
*/
public class BroadcastTreatment {
private static Logger log = LoggerFactory.getLogger(BroadcastTreatment.class);
public void handleNewTreatment(NSTreatment treatment, Context context, boolean isDelta) {
Bundle bundle = new Bundle();
bundle.putString("treatment", treatment.getData().toString());
bundle.putBoolean("delta", isDelta);
Intent intent = new Intent(Intents.ACTION_NEW_TREATMENT);
intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
context.sendBroadcast(intent);
List<ResolveInfo> x = context.getPackageManager().queryBroadcastReceivers(intent, 0);
log.debug("TREAT_ADD " + treatment.getEventType() + " " + x.size() + " receivers");
}
public void handleNewTreatment(JSONArray treatments, Context context, boolean isDelta) {
Bundle bundle = new Bundle();
bundle.putString("treatments", treatments.toString());
bundle.putBoolean("delta", isDelta);
Intent intent = new Intent(Intents.ACTION_NEW_TREATMENT);
intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
context.sendBroadcast(intent);
List<ResolveInfo> x = context.getPackageManager().queryBroadcastReceivers(intent, 0);
log.debug("TREAT_ADD " + treatments.length() + " " + x.size() + " receivers");
}
public void handleChangedTreatment(JSONObject treatment, Context context, boolean isDelta) {
Bundle bundle = new Bundle();
bundle.putString("treatment", treatment.toString());
bundle.putBoolean("delta", isDelta);
Intent intent = new Intent(Intents.ACTION_CHANGED_TREATMENT);
intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
context.sendBroadcast(intent);
List<ResolveInfo> x = context.getPackageManager().queryBroadcastReceivers(intent, 0);
try {
log.debug("TREAT_CHANGE " + treatment.getString("_id") + " " + x.size() + " receivers");
} catch (JSONException e) {}
}
public void handleChangedTreatment(JSONArray treatments, Context context, boolean isDelta) {
Bundle bundle = new Bundle();
bundle.putString("treatments", treatments.toString());
bundle.putBoolean("delta", isDelta);
Intent intent = new Intent(Intents.ACTION_CHANGED_TREATMENT);
intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
context.sendBroadcast(intent);
List<ResolveInfo> x = context.getPackageManager().queryBroadcastReceivers(intent, 0);
log.debug("TREAT_CHANGE " + treatments.length() + " " + x.size() + " receivers");
}
public void handleRemovedTreatment(JSONObject treatment, Context context, boolean isDelta) {
Bundle bundle = new Bundle();
bundle.putString("treatment", treatment.toString());
bundle.putBoolean("delta", isDelta);
Intent intent = new Intent(Intents.ACTION_REMOVED_TREATMENT);
intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
context.sendBroadcast(intent);
List<ResolveInfo> x = context.getPackageManager().queryBroadcastReceivers(intent, 0);
try {
log.debug("TREAT_REMOVE " + treatment.getString("_id") + " " + x.size() + " receivers");
} catch (JSONException e) {}
}
public void handleRemovedTreatment(JSONArray treatments, Context context, boolean isDelta) {
Bundle bundle = new Bundle();
bundle.putString("treatments", treatments.toString());
bundle.putBoolean("delta", isDelta);
Intent intent = new Intent(Intents.ACTION_REMOVED_TREATMENT);
intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
context.sendBroadcast(intent);
List<ResolveInfo> x = context.getPackageManager().queryBroadcastReceivers(intent, 0);
log.debug("TREAT_REMOVE " + treatments.length() + " treatments " + x.size() + " receivers");
}
}

View file

@ -1,4 +1,4 @@
package info.nightscout.client.data; package info.nightscout.androidaps.plugins.NSClientInternal.data;
import android.content.Intent; import android.content.Intent;
import android.content.pm.ResolveInfo; import android.content.pm.ResolveInfo;

View file

@ -0,0 +1,87 @@
package info.nightscout.androidaps.plugins.NSClientInternal.data;
import com.google.common.base.Charsets;
import com.google.common.hash.Hashing;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Created by mike on 27.02.2016.
* <p>
* Allowed actions "dbAdd" || "dbUpdate" || "dbUpdateUnset" || "dbRemove"
*/
public class DbRequest {
public String action = null;
public String collection = null;
public JSONObject data = null;
public String _id = null;
public String nsClientID = null;
public DbRequest() {
}
// dbAdd
public DbRequest(String action, String collection, String nsClientID, JSONObject data) {
this.action = action;
this.collection = collection;
this.data = data;
this.nsClientID = nsClientID;
this._id = "";
}
// dbUpdate, dbUpdateUnset
public DbRequest(String action, String collection, String nsClientID, String _id, JSONObject data) {
this.action = action;
this.collection = collection;
this.data = data;
this.nsClientID = nsClientID;
this._id = _id;
}
// dbRemove
public DbRequest(String action, String collection, String nsClientID, String _id) {
this.action = action;
this.collection = collection;
this.data = new JSONObject();
this.nsClientID = nsClientID;
this._id = _id;
}
public String hash() {
return Hashing.sha1().hashString(action + collection + _id + data.toString(), Charsets.UTF_8).toString();
}
public JSONObject toJSON() {
JSONObject object = new JSONObject();
try {
object.put("action", action);
object.put("collection", collection);
object.put("data", data);
if (_id != null) object.put("_id", _id);
if (nsClientID != null) object.put("nsClientID", nsClientID);
} catch (JSONException e) {
e.printStackTrace();
}
return object;
}
public static DbRequest fromJSON(JSONObject jsonObject) {
DbRequest result = new DbRequest();
try {
if (jsonObject.has("action"))
result.action = jsonObject.getString("action");
if (jsonObject.has("collection"))
result.collection = jsonObject.getString("collection");
if (jsonObject.has("data"))
result.data = jsonObject.getJSONObject("data");
if (jsonObject.has("_id"))
result._id = jsonObject.getString("_id");
if (jsonObject.has("nsClientID"))
result.nsClientID = jsonObject.getString("nsClientID");
} catch (JSONException e) {
e.printStackTrace();
}
return result;
}
}

View file

@ -1,9 +1,12 @@
package info.nightscout.client.data; package info.nightscout.androidaps.plugins.NSClientInternal.data;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class NSCal { public class NSCal {
private static Logger log = LoggerFactory.getLogger(NSCal.class);
public long date; public long date;
public double slope; public double slope;
public double intercept; public double intercept;
@ -17,6 +20,7 @@ public class NSCal {
scale = json.getDouble("scale"); scale = json.getDouble("scale");
} catch (JSONException e) { } catch (JSONException e) {
e.printStackTrace(); e.printStackTrace();
log.debug("Data: " + json.toString());
} }
} }
} }

View file

@ -1,4 +1,4 @@
package info.nightscout.client.data; package info.nightscout.androidaps.plugins.NSClientInternal.data;
import com.crashlytics.android.Crashlytics; import com.crashlytics.android.Crashlytics;

View file

@ -1,4 +1,4 @@
package info.nightscout.client.data; package info.nightscout.androidaps.plugins.NSClientInternal.data;
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.client.data; package info.nightscout.androidaps.plugins.NSClientInternal.data;
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.client.data; package info.nightscout.androidaps.plugins.NSClientInternal.data;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;

View file

@ -0,0 +1,30 @@
package info.nightscout.androidaps.plugins.NSClientInternal.events;
import android.text.Html;
import android.text.Spanned;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Created by mike on 15.02.2017.
*/
public class EventNSClientNewLog {
public Date date = new Date();
public String action;
public String logText;
public EventNSClientNewLog(String action, String logText) {
this.action = action;
this.logText = logText;
}
public Spanned toHtml() {
SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
Spanned line = Html.fromHtml(timeFormat.format(date) + " <b>" + action + "</b> " + logText + "<br>");
return line;
}
}

View file

@ -0,0 +1,8 @@
package info.nightscout.androidaps.plugins.NSClientInternal.events;
/**
* Created by mike on 15.02.2017.
*/
public class EventNSClientRestart {
}

View file

@ -0,0 +1,16 @@
package info.nightscout.androidaps.plugins.NSClientInternal.events;
/**
* Created by mike on 02.01.2016.
*/
public class EventNSClientStatus {
public String status = "";
public EventNSClientStatus(String status) {
this.status = status;
}
public EventNSClientStatus() {
}
}

View file

@ -0,0 +1,8 @@
package info.nightscout.androidaps.plugins.NSClientInternal.events;
/**
* Created by mike on 17.02.2017.
*/
public class EventNSClientUpdateGUI {
}

View file

@ -0,0 +1,17 @@
package info.nightscout.androidaps.plugins.NSClientInternal.receivers;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import info.nightscout.androidaps.plugins.NSClientInternal.services.NSClientService;
public class AutoStartReceiver extends BroadcastReceiver {
public AutoStartReceiver() {
}
@Override
public void onReceive(Context context, Intent intent) {
context.startService(new Intent(context, NSClientService.class));
}
}

View file

@ -0,0 +1,93 @@
package info.nightscout.androidaps.plugins.NSClientInternal.receivers;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.PowerManager;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.plugins.NSClientInternal.NSClientInternalPlugin;
import info.nightscout.androidaps.plugins.NSClientInternal.UploadQueue;
import info.nightscout.androidaps.plugins.NSClientInternal.data.DbRequest;
public class DBAccessReceiver extends BroadcastReceiver {
private static Logger log = LoggerFactory.getLogger(DBAccessReceiver.class);
@Override
public void onReceive(Context context, Intent intent) {
PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"sendQueue");
NSClientInternalPlugin nsClientInternalPlugin = (NSClientInternalPlugin) MainApp.getSpecificPlugin(NSClientInternalPlugin.class);
if (!nsClientInternalPlugin.isEnabled(PluginBase.GENERAL)) {
return;
}
wakeLock.acquire();
try {
Bundle bundles = intent.getExtras();
if (bundles == null) return;
if (!bundles.containsKey("action")) return;
String collection = null;
String _id = null;
JSONObject data = null;
String action = bundles.getString("action");
try { collection = bundles.getString("collection"); } catch (Exception e) {}
try { _id = bundles.getString("_id"); } catch (Exception e) {}
try { data = new JSONObject(bundles.getString("data")); } catch (Exception e) {}
if (data == null && !action.equals("dbRemove") || _id == null && action.equals("dbRemove")) {
log.debug("DBACCESS no data inside record");
return;
}
if (action.equals("dbRemove")) {
data = new JSONObject();
}
// mark by id
Long nsclientid = new Date().getTime();
try {
data.put("NSCLIENT_ID", nsclientid);
} catch (JSONException e) {
e.printStackTrace();
}
if (!isAllowedCollection(collection)) {
log.debug("DBACCESS wrong collection specified");
return;
}
if (action.equals("dbRemove")) {
DbRequest dbr = new DbRequest(action, collection, nsclientid.toString(), _id);
UploadQueue.add(dbr);
} else {
DbRequest dbr = new DbRequest(action, collection, nsclientid.toString(), data);
UploadQueue.add(dbr);
}
} finally {
wakeLock.release();
}
}
private boolean isAllowedCollection(String collection) {
// "treatments" || "entries" || "devicestatus" || "profile" || "food"
if (collection.equals("treatments")) return true;
if (collection.equals("entries")) return true;
if (collection.equals("devicestatus")) return true;
if (collection.equals("profile")) return true;
if (collection.equals("food")) return true;
return false;
}
}

View file

@ -0,0 +1,25 @@
package info.nightscout.androidaps.plugins.NSClientInternal.receivers;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.support.v4.content.WakefulBroadcastReceiver;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.plugins.NSClientInternal.events.EventNSClientRestart;
import info.nightscout.androidaps.plugins.NSClientInternal.services.NSClientService;
public class RestartReceiver extends WakefulBroadcastReceiver {
public RestartReceiver() {
}
@Override
public void onReceive(Context context, Intent intent) {
startWakefulService(context, new Intent(context, NSClientService.class)
.setAction(intent.getAction())
.putExtras(intent));
MainApp.bus().post(new EventNSClientRestart());
completeWakefulIntent(intent);
}
}

View file

@ -0,0 +1,676 @@
package info.nightscout.androidaps.plugins.NSClientInternal.services;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Binder;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.PowerManager;
import android.preference.PreferenceManager;
import com.google.common.base.Charsets;
import com.google.common.hash.Hashing;
import com.squareup.otto.Subscribe;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.URISyntaxException;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.events.EventAppExit;
import info.nightscout.androidaps.events.EventConfigBuilderChange;
import info.nightscout.androidaps.events.EventPreferenceChange;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.plugins.DanaR.Services.ExecutionService;
import info.nightscout.androidaps.plugins.NSClientInternal.NSClientInternalPlugin;
import info.nightscout.androidaps.plugins.NSClientInternal.UploadQueue;
import info.nightscout.androidaps.plugins.NSClientInternal.acks.NSAddAck;
import info.nightscout.androidaps.plugins.NSClientInternal.acks.NSAuthAck;
import info.nightscout.androidaps.plugins.NSClientInternal.acks.NSPingAck;
import info.nightscout.androidaps.plugins.NSClientInternal.acks.NSUpdateAck;
import info.nightscout.androidaps.plugins.NSClientInternal.broadcasts.BroadcastCals;
import info.nightscout.androidaps.plugins.NSClientInternal.broadcasts.BroadcastDeviceStatus;
import info.nightscout.androidaps.plugins.NSClientInternal.broadcasts.BroadcastMbgs;
import info.nightscout.androidaps.plugins.NSClientInternal.broadcasts.BroadcastProfile;
import info.nightscout.androidaps.plugins.NSClientInternal.broadcasts.BroadcastSgvs;
import info.nightscout.androidaps.plugins.NSClientInternal.broadcasts.BroadcastStatus;
import info.nightscout.androidaps.plugins.NSClientInternal.broadcasts.BroadcastTreatment;
import info.nightscout.androidaps.plugins.NSClientInternal.data.DbRequest;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSCal;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSSgv;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSStatus;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSTreatment;
import info.nightscout.androidaps.plugins.NSClientInternal.events.EventNSClientNewLog;
import info.nightscout.androidaps.plugins.NSClientInternal.events.EventNSClientStatus;
import info.nightscout.androidaps.plugins.Overview.Notification;
import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification;
import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification;
import info.nightscout.utils.DateUtil;
import info.nightscout.utils.SP;
import io.socket.client.IO;
import io.socket.client.Socket;
import io.socket.emitter.Emitter;
public class NSClientService extends Service {
private static Logger log = LoggerFactory.getLogger(ExecutionService.class);
static public PowerManager.WakeLock mWakeLock;
private IBinder mBinder = new NSClientService.LocalBinder();
static NSProfile nsProfile;
static public Handler handler;
static private HandlerThread handlerThread;
public static Socket mSocket;
public static boolean isConnected = false;
public static boolean hasWriteAuth = false;
private static Integer dataCounter = 0;
public static String nightscoutVersionName = "";
public static Integer nightscoutVersionCode = 0;
private boolean nsEnabled = false;
static public String nsURL = "";
private String nsAPISecret = "";
private String nsDevice = "";
private Integer nsHours = 3;
private final Integer timeToWaitForResponseInMs = 30000;
private boolean uploading = false;
public Date lastReception = new Date();
public long latestDateInReceivedData = 0;
private String nsAPIhashCode = "";
public static UploadQueue uploadQueue = new UploadQueue();
public NSClientService() {
registerBus();
if (handler == null) {
handlerThread = new HandlerThread(NSClientService.class.getSimpleName() + "Handler");
handlerThread.start();
handler = new Handler(handlerThread.getLooper());
}
PowerManager powerManager = (PowerManager) MainApp.instance().getApplicationContext().getSystemService(Context.POWER_SERVICE);
mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "NSClientService");
initialize();
}
public class LocalBinder extends Binder {
public NSClientService getServiceInstance() {
return NSClientService.this;
}
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
private void registerBus() {
try {
MainApp.bus().unregister(this);
} catch (RuntimeException x) {
// Ignore
}
MainApp.bus().register(this);
}
@Subscribe
public void onStatusEvent(EventAppExit event) {
if (Config.logFunctionCalls)
log.debug("EventAppExit received");
destroy();
stopSelf();
if (Config.logFunctionCalls)
log.debug("EventAppExit finished");
}
@Subscribe
public void onStatusEvent(EventPreferenceChange ev) {
if (ev.isChanged(R.string.key_nsclientinternal_url) ||
ev.isChanged(R.string.key_nsclientinternal_api_secret) ||
ev.isChanged(R.string.key_nsclientinternal_hours) ||
ev.isChanged(R.string.key_nsclientinternal_paused)
) {
destroy();
initialize();
}
}
@Subscribe
public void onStatusEvent(EventConfigBuilderChange ev) {
if (nsEnabled != MainApp.getSpecificPlugin(NSClientInternalPlugin.class).isEnabled(PluginBase.GENERAL)) {
destroy();
initialize();
}
}
public static void setNsProfile(NSProfile profile) {
nsProfile = profile;
}
public static NSProfile getNsProfile() {
return nsProfile;
}
public void initialize() {
dataCounter = 0;
NSClientService.mWakeLock.acquire();
readPreferences();
if (!nsAPISecret.equals(""))
nsAPIhashCode = Hashing.sha1().hashString(nsAPISecret, Charsets.UTF_8).toString();
MainApp.bus().post(new EventNSClientStatus("Initializing"));
if (((NSClientInternalPlugin)MainApp.getSpecificPlugin(NSClientInternalPlugin.class)).paused) {
MainApp.bus().post(new EventNSClientNewLog("NSCLIENT", "paused"));
MainApp.bus().post(new EventNSClientStatus("Paused"));
} else if (!nsEnabled) {
MainApp.bus().post(new EventNSClientNewLog("NSCLIENT", "disabled"));
MainApp.bus().post(new EventNSClientStatus("Disabled"));
} else if (!nsURL.equals("")) {
try {
MainApp.bus().post(new EventNSClientStatus("Connecting ..."));
IO.Options opt = new IO.Options();
opt.forceNew = true;
opt.reconnection = true;
mSocket = IO.socket(nsURL, opt);
mSocket.on(Socket.EVENT_CONNECT, onConnect);
mSocket.on(Socket.EVENT_DISCONNECT, onDisconnect);
mSocket.on(Socket.EVENT_PING, onPing);
MainApp.bus().post(new EventNSClientNewLog("NSCLIENT", "do connect"));
mSocket.connect();
mSocket.on("dataUpdate", onDataUpdate);
} catch (URISyntaxException | RuntimeException e) {
MainApp.bus().post(new EventNSClientNewLog("NSCLIENT", "Wrong URL syntax"));
MainApp.bus().post(new EventNSClientStatus("Wrong URL syntax"));
}
} else {
MainApp.bus().post(new EventNSClientNewLog("NSCLIENT", "No NS URL specified"));
MainApp.bus().post(new EventNSClientStatus("Not configured"));
}
NSClientService.mWakeLock.release();
}
private Emitter.Listener onConnect = new Emitter.Listener() {
@Override
public void call(Object... args) {
MainApp.bus().post(new EventNSClientNewLog("NSCLIENT", "connect event. ID: " + mSocket.id()));
sendAuthMessage(new NSAuthAck());
}
};
private Emitter.Listener onDisconnect = new Emitter.Listener() {
@Override
public void call(Object... args) {
MainApp.bus().post(new EventNSClientNewLog("NSCLIENT", "disconnect event"));
}
};
public void destroy() {
if (mSocket != null) {
MainApp.bus().post(new EventNSClientNewLog("NSCLIENT", "destroy"));
isConnected = false;
hasWriteAuth = false;
mSocket.disconnect();
mSocket = null;
}
}
public void sendAuthMessage(NSAuthAck ack) {
JSONObject authMessage = new JSONObject();
try {
authMessage.put("client", "Android_" + nsDevice);
authMessage.put("history", nsHours);
authMessage.put("status", true); // receive status
authMessage.put("pingme", true); // send mi pings to keep alive
authMessage.put("from", latestDateInReceivedData); // send data newer than
authMessage.put("secret", nsAPIhashCode);
} catch (JSONException e) {
e.printStackTrace();
return;
}
MainApp.bus().post(new EventNSClientNewLog("AUTH", "requesting auth"));
mSocket.emit("authorize", authMessage, ack);
}
@Subscribe
public void onStatusEvent(NSAuthAck ack) {
String connectionStatus = "Authenticated (";
if (ack.read) connectionStatus += "R";
if (ack.write) connectionStatus += "W";
if (ack.write_treatment) connectionStatus += "T";
connectionStatus += ')';
isConnected = true;
hasWriteAuth = ack.write && ack.write_treatment;
MainApp.bus().post(new EventNSClientStatus(connectionStatus));
MainApp.bus().post(new EventNSClientNewLog("AUTH", connectionStatus));
if (!ack.write) {
MainApp.bus().post(new EventNSClientNewLog("ERROR", "Write permission not granted !!!!"));
}
if (!ack.write_treatment) {
MainApp.bus().post(new EventNSClientNewLog("ERROR", "Write treatment permission not granted !!!!"));
}
if (!hasWriteAuth) {
Notification noperm = new Notification(Notification.NSCLIENT_NO_WRITE_PERMISSION, MainApp.sResources.getString(R.string.nowritepermission), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(noperm));
} else {
MainApp.bus().post(new EventDismissNotification(Notification.NSCLIENT_NO_WRITE_PERMISSION));
}
lastReception = new Date();
}
public void readPreferences() {
nsEnabled = MainApp.getSpecificPlugin(NSClientInternalPlugin.class).isEnabled(PluginBase.GENERAL);
nsURL = SP.getString(R.string.key_nsclientinternal_url, "");
nsAPISecret = SP.getString(R.string.key_nsclientinternal_api_secret, "");
nsHours = SP.getInt(R.string.key_nsclientinternal_hours, 3);
nsDevice = SP.getString("careportal_enteredby", "");
}
private Emitter.Listener onPing = new Emitter.Listener() {
@Override
public void call(final Object... args) {
if (Config.detailedLog)
MainApp.bus().post(new EventNSClientNewLog("PING", "received"));
// send data if there is something waiting
resend("Ping received");
}
};
private Emitter.Listener onDataUpdate = new Emitter.Listener() {
@Override
public void call(final Object... args) {
lastReception = new Date();
NSClientService.handler.post(new Runnable() {
@Override
public void run() {
PowerManager powerManager = (PowerManager) MainApp.instance().getApplicationContext().getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"onDataUpdate");
wakeLock.acquire();
try {
SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext());
JSONObject data = (JSONObject) args[0];
NSCal actualCal = new NSCal();
boolean broadcastProfile = false;
try {
// delta means only increment/changes are comming
boolean isDelta = data.has("delta");
boolean isFull = !isDelta;
MainApp.bus().post(new EventNSClientNewLog("DATA", "Data packet #" + dataCounter++ + (isDelta ? " delta" : " full")));
if (data.has("profiles")) {
JSONArray profiles = (JSONArray) data.getJSONArray("profiles");
if (profiles.length() > 0) {
JSONObject profile = (JSONObject) profiles.get(profiles.length() - 1);
String activeProfile = NSClientService.getNsProfile() == null ? null : NSClientService.getNsProfile().getActiveProfile();
NSProfile nsProfile = new NSProfile(profile, activeProfile);
NSClientService.setNsProfile(nsProfile);
broadcastProfile = true;
MainApp.bus().post(new EventNSClientNewLog("PROFILE", "profile received"));
}
}
if (data.has("status")) {
JSONObject status = data.getJSONObject("status");
NSStatus nsStatus = new NSStatus(status);
if (!status.has("versionNum")) {
if (status.getInt("versionNum") < 900) {
MainApp.bus().post(new EventNSClientNewLog("ERROR", "Unsupported Nightscout version !!!!"));
}
} else {
nightscoutVersionName = status.getString("version");
nightscoutVersionCode = status.getInt("versionNum");
}
BroadcastStatus bs = new BroadcastStatus();
bs.handleNewStatus(nsStatus, MainApp.instance().getApplicationContext(), isDelta);
if (NSClientService.getNsProfile() != null) {
String oldActiveProfile = NSClientService.getNsProfile().getActiveProfile();
String receivedActiveProfile = nsStatus.getActiveProfile();
NSClientService.getNsProfile().setActiveProfile(receivedActiveProfile);
if (receivedActiveProfile != null) {
MainApp.bus().post(new EventNSClientNewLog("PROFILE", "status activeProfile received: " + receivedActiveProfile));
}
// Change possible nulls to ""
String oldP = oldActiveProfile == null ? "" : oldActiveProfile;
String newP = receivedActiveProfile == null ? "" : receivedActiveProfile;
if (!newP.equals(oldP)) {
broadcastProfile = true;
}
}
/* Other received data to 2016/02/10
{
status: 'ok'
, name: env.name
, version: env.version
, versionNum: versionNum (for ver 1.2.3 contains 10203)
, serverTime: new Date().toISOString()
, apiEnabled: apiEnabled
, careportalEnabled: apiEnabled && env.settings.enable.indexOf('careportal') > -1
, boluscalcEnabled: apiEnabled && env.settings.enable.indexOf('boluscalc') > -1
, head: env.head
, settings: env.settings
, extendedSettings: ctx.plugins && ctx.plugins.extendedClientSettings ? ctx.plugins.extendedClientSettings(env.extendedSettings) : {}
, activeProfile ..... calculated from treatments or missing
}
*/
} else if (!isDelta) {
MainApp.bus().post(new EventNSClientNewLog("ERROR", "Unsupported Nightscout version !!!!"));
}
// If new profile received or change detected broadcast it
if (broadcastProfile && nsProfile != null) {
BroadcastProfile bp = new BroadcastProfile();
bp.handleNewTreatment(nsProfile, MainApp.instance().getApplicationContext(), isDelta);
MainApp.bus().post(new EventNSClientNewLog("PROFILE", "broadcasting"));
}
if (data.has("treatments")) {
JSONArray treatments = (JSONArray) data.getJSONArray("treatments");
JSONArray removedTreatments = new JSONArray();
JSONArray updatedTreatments = new JSONArray();
JSONArray addedTreatments = new JSONArray();
BroadcastTreatment bt = new BroadcastTreatment();
if (treatments.length() > 0)
MainApp.bus().post(new EventNSClientNewLog("DATA", "received " + treatments.length() + " treatments"));
for (Integer index = 0; index < treatments.length(); index++) {
JSONObject jsonTreatment = treatments.getJSONObject(index);
NSTreatment treatment = new NSTreatment(jsonTreatment);
// remove from upload queue if Ack is failing
UploadQueue.removeID(jsonTreatment);
//Find latest date in treatment
if (treatment.getMills() != null && treatment.getMills() < new Date().getTime())
if (treatment.getMills() > latestDateInReceivedData)
latestDateInReceivedData = treatment.getMills();
if (treatment.getAction() == null) {
if (!isCurrent(treatment)) continue;
addedTreatments.put(jsonTreatment);
} else if (treatment.getAction().equals("update")) {
if (!isCurrent(treatment)) continue;
updatedTreatments.put(jsonTreatment);
} else if (treatment.getAction().equals("remove")) {
removedTreatments.put(jsonTreatment);
}
}
if (removedTreatments.length() > 0) {
bt.handleRemovedTreatment(removedTreatments, MainApp.instance().getApplicationContext(), isDelta);
}
if (updatedTreatments.length() > 0) {
bt.handleChangedTreatment(updatedTreatments, MainApp.instance().getApplicationContext(), isDelta);
}
if (addedTreatments.length() > 0) {
bt.handleNewTreatment(addedTreatments, MainApp.instance().getApplicationContext(), isDelta);
}
}
if (data.has("devicestatus")) {
BroadcastDeviceStatus bds = new BroadcastDeviceStatus();
JSONArray devicestatuses = (JSONArray) data.getJSONArray("devicestatus");
if (devicestatuses.length() > 0) {
MainApp.bus().post(new EventNSClientNewLog("DATA", "received " + devicestatuses.length() + " devicestatuses"));
for (Integer index = 0; index < devicestatuses.length(); index++) {
JSONObject jsonStatus = devicestatuses.getJSONObject(index);
// remove from upload queue if Ack is failing
UploadQueue.removeID(jsonStatus);
}
// send only last record
bds.handleNewDeviceStatus(devicestatuses.getJSONObject(devicestatuses.length() - 1), MainApp.instance().getApplicationContext(), isDelta);
}
}
if (data.has("mbgs")) {
BroadcastMbgs bmbg = new BroadcastMbgs();
JSONArray mbgs = (JSONArray) data.getJSONArray("mbgs");
if (mbgs.length() > 0)
MainApp.bus().post(new EventNSClientNewLog("DATA", "received " + mbgs.length() + " mbgs"));
for (Integer index = 0; index < mbgs.length(); index++) {
JSONObject jsonMbg = mbgs.getJSONObject(index);
// remove from upload queue if Ack is failing
UploadQueue.removeID(jsonMbg);
}
bmbg.handleNewMbg(mbgs, MainApp.instance().getApplicationContext(), isDelta);
}
if (data.has("cals")) {
BroadcastCals bc = new BroadcastCals();
JSONArray cals = (JSONArray) data.getJSONArray("cals");
if (cals.length() > 0)
MainApp.bus().post(new EventNSClientNewLog("DATA", "received " + cals.length() + " cals"));
// Retreive actual calibration
for (Integer index = 0; index < cals.length(); index++) {
if (index == 0) {
actualCal.set(cals.optJSONObject(index));
}
// remove from upload queue if Ack is failing
UploadQueue.removeID(cals.optJSONObject(index));
}
bc.handleNewCal(cals, MainApp.instance().getApplicationContext(), isDelta);
}
if (data.has("sgvs")) {
BroadcastSgvs bs = new BroadcastSgvs();
String units = nsProfile != null ? nsProfile.getUnits() : "mg/dl";
JSONArray sgvs = (JSONArray) data.getJSONArray("sgvs");
if (sgvs.length() > 0)
MainApp.bus().post(new EventNSClientNewLog("DATA", "received " + sgvs.length() + " sgvs"));
for (Integer index = 0; index < sgvs.length(); index++) {
JSONObject jsonSgv = sgvs.getJSONObject(index);
// MainApp.bus().post(new EventNSClientNewLog("DATA", "svg " + sgvs.getJSONObject(index).toString());
NSSgv sgv = new NSSgv(jsonSgv);
// Handle new sgv here
// remove from upload queue if Ack is failing
UploadQueue.removeID(jsonSgv);
//Find latest date in sgv
if (sgv.getMills() != null && sgv.getMills() < new Date().getTime())
if (sgv.getMills() > latestDateInReceivedData)
latestDateInReceivedData = sgv.getMills();
}
bs.handleNewSgv(sgvs, MainApp.instance().getApplicationContext(), isDelta);
}
MainApp.bus().post(new EventNSClientNewLog("LAST", DateUtil.dateAndTimeString(latestDateInReceivedData)));
} catch (JSONException e) {
e.printStackTrace();
}
//MainApp.bus().post(new EventNSClientNewLog("NSCLIENT", "onDataUpdate end");
} finally {
wakeLock.release();
}
}
});
}
};
public void dbUpdate(DbRequest dbr, NSUpdateAck ack) {
try {
if (!isConnected || !hasWriteAuth) return;
JSONObject message = new JSONObject();
message.put("collection", dbr.collection);
message.put("_id", dbr._id);
message.put("data", dbr.data);
mSocket.emit("dbUpdate", message, ack);
MainApp.bus().post(new EventNSClientNewLog("DBUPDATE " + dbr.collection, "Sent " + dbr._id));
} catch (JSONException e) {
e.printStackTrace();
}
}
public void dbUpdateUnset(DbRequest dbr, NSUpdateAck ack) {
try {
if (!isConnected || !hasWriteAuth) return;
JSONObject message = new JSONObject();
message.put("collection", dbr.collection);
message.put("_id", dbr._id);
message.put("data", dbr.data);
mSocket.emit("dbUpdateUnset", message, ack);
MainApp.bus().post(new EventNSClientNewLog("DBUPDATEUNSET " + dbr.collection, "Sent " + dbr._id));
} catch (JSONException e) {
e.printStackTrace();
}
}
public void dbRemove(DbRequest dbr, NSUpdateAck ack) {
try {
if (!isConnected || !hasWriteAuth) return;
JSONObject message = new JSONObject();
message.put("collection", dbr.collection);
message.put("_id", dbr._id);
mSocket.emit("dbRemove", message, ack);
MainApp.bus().post(new EventNSClientNewLog("DBREMOVE " + dbr.collection, "Sent " + dbr._id));
} catch (JSONException e) {
e.printStackTrace();
}
}
@Subscribe
public void onStatusEvent(NSUpdateAck ack) {
if (ack.result) {
uploadQueue.removeID(ack.action, ack._id);
MainApp.bus().post(new EventNSClientNewLog("DBUPDATE/DBREMOVE", "Acked " + ack._id));
} else {
MainApp.bus().post(new EventNSClientNewLog("ERROR", "DBUPDATE/DBREMOVE Unknown response"));
}
}
public void dbAdd(DbRequest dbr, NSAddAck ack) {
try {
if (!isConnected || !hasWriteAuth) return;
JSONObject message = new JSONObject();
message.put("collection", dbr.collection);
message.put("data", dbr.data);
mSocket.emit("dbAdd", message, ack);
MainApp.bus().post(new EventNSClientNewLog("DBADD " + dbr.collection, "Sent " + dbr.nsClientID));
} catch (JSONException e) {
e.printStackTrace();
}
}
@Subscribe
public void onStatusEvent(NSAddAck ack) {
if (ack.nsClientID != null) {
uploadQueue.removeID(ack.json);
MainApp.bus().post(new EventNSClientNewLog("DBADD", "Acked " + ack.nsClientID));
} else {
MainApp.bus().post(new EventNSClientNewLog("ERROR", "DBADD Unknown response"));
}
}
public void doPing() {
if (!isConnected || !hasWriteAuth) return;
MainApp.bus().post(new EventNSClientNewLog("PING", "Sending"));
uploading = true;
JSONObject message = new JSONObject();
try {
message.put("mills", new Date().getTime());
} catch (JSONException e) {
e.printStackTrace();
}
NSPingAck ack = new NSPingAck();
mSocket.emit("nsping", message, ack);
synchronized (ack) {
try {
ack.wait(timeToWaitForResponseInMs);
} catch (InterruptedException e) {
}
}
if (ack.received) {
String connectionStatus = "Pong received";
if (ack.auth_received) {
connectionStatus += ": ";
if (ack.read) connectionStatus += "R";
if (ack.write) connectionStatus += "W";
if (ack.write_treatment) connectionStatus += "T";
}
if (!ack.read) sendAuthMessage(new NSAuthAck());
MainApp.bus().post(new EventNSClientNewLog("AUTH ", connectionStatus));
} else {
MainApp.bus().post(new EventNSClientNewLog("PING", "Ping lost"));
}
uploading = false;
}
private boolean isCurrent(NSTreatment treatment) {
long now = (new Date()).getTime();
long minPast = now - nsHours * 60L * 60 * 1000;
if (treatment.getMills() == null) {
log.debug("treatment.getMills() == null " + treatment.getData().toString());
return false;
}
if (treatment.getMills() > minPast) return true;
return false;
}
public void resend(final String reason) {
if (UploadQueue.queue.size() == 0)
return;
if (!isConnected || !hasWriteAuth) return;
MainApp.bus().post(new EventNSClientNewLog("QUEUE", "Resend started: " + reason));
handler.post(new Runnable() {
@Override
public void run() {
Logger log = LoggerFactory.getLogger(UploadQueue.class);
Iterator<Map.Entry<String, DbRequest>> iter = UploadQueue.queue.entrySet().iterator();
if (mSocket == null || !mSocket.connected()) return;
while (iter.hasNext()) {
DbRequest dbr = iter.next().getValue();
if (dbr.action.equals("dbAdd")) {
NSAddAck addAck = new NSAddAck();
dbAdd(dbr, addAck);
} else if (dbr.action.equals("dbRemove")) {
NSUpdateAck removeAck = new NSUpdateAck(dbr.action, dbr._id);
dbRemove(dbr, removeAck);
} else if (dbr.action.equals("dbUpdate")) {
NSUpdateAck updateAck = new NSUpdateAck(dbr.action, dbr._id);
dbUpdate(dbr, updateAck);
} else if (dbr.action.equals("dbUpdateUnset")) {
NSUpdateAck updateUnsetAck = new NSUpdateAck(dbr.action, dbr._id);
dbUpdateUnset(dbr, updateUnsetAck);
}
}
MainApp.bus().post(new EventNSClientNewLog("QUEUE", "Resend ended: " + reason));
}
});
}
public void restart() {
destroy();
initialize();
}
}

View file

@ -19,8 +19,9 @@ import info.nightscout.androidaps.Services.Intents;
import info.nightscout.androidaps.events.EventNewBasalProfile; import info.nightscout.androidaps.events.EventNewBasalProfile;
import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.ProfileInterface; import info.nightscout.androidaps.interfaces.ProfileInterface;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.androidaps.plugins.NSProfile.events.EventNSProfileUpdateGUI; import info.nightscout.androidaps.plugins.NSProfile.events.EventNSProfileUpdateGUI;
import info.nightscout.client.data.NSProfile; import info.nightscout.utils.SP;
/** /**
* Created by mike on 05.08.2016. * Created by mike on 05.08.2016.
@ -110,9 +111,8 @@ public class NSProfilePlugin implements PluginBase, ProfileInterface {
private void loadNSProfile() { private void loadNSProfile() {
if (Config.logPrefsChange) if (Config.logPrefsChange)
log.debug("Loading stored profile"); log.debug("Loading stored profile");
SharedPreferences store = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext()); String activeProfile = SP.getString("activeProfile", null);
String activeProfile = store.getString("activeProfile", null); String profileString = SP.getString("profile", null);
String profileString = store.getString("profile", null);
if (profileString != null) { if (profileString != null) {
if (Config.logPrefsChange) { if (Config.logPrefsChange) {
log.debug("Loaded profile: " + profileString); log.debug("Loaded profile: " + profileString);

View file

@ -16,6 +16,7 @@ import info.nightscout.androidaps.R;
import info.nightscout.androidaps.interfaces.ConstraintsInterface; import info.nightscout.androidaps.interfaces.ConstraintsInterface;
import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.plugins.Loop.LoopPlugin; import info.nightscout.androidaps.plugins.Loop.LoopPlugin;
import info.nightscout.utils.SP;
import info.nightscout.utils.SafeParse; import info.nightscout.utils.SafeParse;
/** /**
@ -211,20 +212,19 @@ public class ObjectivesPlugin implements PluginBase, ConstraintsInterface {
} }
void loadProgress() { void loadProgress() {
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext());
for (int num = 0; num < objectives.size(); num++) { for (int num = 0; num < objectives.size(); num++) {
Objective o = objectives.get(num); Objective o = objectives.get(num);
try { try {
o.started = new Date(SafeParse.stringToLong(settings.getString("Objectives" + num + "started", "0"))); o.started = new Date(SP.getLong("Objectives" + num + "started", 0L));
o.accomplished = new Date(SafeParse.stringToLong(settings.getString("Objectives" + num + "accomplished", "0"))); o.accomplished = new Date(SP.getLong("Objectives" + num + "accomplished", 0L));
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
bgIsAvailableInNS = settings.getBoolean("Objectives" + "bgIsAvailableInNS", false); bgIsAvailableInNS = SP.getBoolean("Objectives" + "bgIsAvailableInNS", false);
pumpStatusIsAvailableInNS = settings.getBoolean("Objectives" + "pumpStatusIsAvailableInNS", false); pumpStatusIsAvailableInNS = SP.getBoolean("Objectives" + "pumpStatusIsAvailableInNS", false);
try { try {
manualEnacts = SafeParse.stringToInt(settings.getString("Objectives" + "manualEnacts", "0")); manualEnacts = SP.getInt("Objectives" + "manualEnacts", 0);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }

View file

@ -1,8 +1,5 @@
package info.nightscout.androidaps.plugins.OpenAPSAMA; package info.nightscout.androidaps.plugins.OpenAPSAMA;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -11,12 +8,12 @@ import java.util.Arrays;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.data.IobTotal; import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.db.BgReading; import info.nightscout.androidaps.db.BgReading;
import info.nightscout.client.data.NSProfile; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.utils.Round; import info.nightscout.utils.Round;
import info.nightscout.utils.SP;
import info.nightscout.utils.SafeParse; import info.nightscout.utils.SafeParse;
@ -24,7 +21,6 @@ public class Autosens {
private static Logger log = LoggerFactory.getLogger(Autosens.class); private static Logger log = LoggerFactory.getLogger(Autosens.class);
public static AutosensResult detectSensitivityandCarbAbsorption(List<BgReading> glucose_data, Long mealTime) { public static AutosensResult detectSensitivityandCarbAbsorption(List<BgReading> glucose_data, Long mealTime) {
SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext());
NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile(); NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile();
//console.error(mealTime); //console.error(mealTime);
@ -132,7 +128,7 @@ public class Autosens {
if (mealTime != null && bgTime > mealTime) { if (mealTime != null && bgTime > mealTime) {
// figure out how many carbs that represents // figure out how many carbs that represents
// but always assume at least 3mg/dL/5m (default) absorption // but always assume at least 3mg/dL/5m (default) absorption
double ci = Math.max(deviation, SafeParse.stringToDouble(SP.getString("openapsama_min_5m_carbimpact", "3.0"))); double ci = Math.max(deviation, SP.getDouble("openapsama_min_5m_carbimpact", 3.0));
double absorbed = ci * profile.getIc(secondsFromMidnight) / sens; double absorbed = ci * profile.getIc(secondsFromMidnight) / sens;
// and add that to the running total carbsAbsorbed // and add that to the running total carbsAbsorbed
carbsAbsorbed += absorbed; carbsAbsorbed += absorbed;

View file

@ -16,17 +16,15 @@ import org.slf4j.LoggerFactory;
import java.io.IOException; import java.io.IOException;
import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.data.GlucoseStatus; import info.nightscout.androidaps.data.GlucoseStatus;
import info.nightscout.androidaps.data.MealData; import info.nightscout.androidaps.data.MealData;
import info.nightscout.androidaps.db.TempBasal; import info.nightscout.androidaps.db.TempBasal;
import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderFragment;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.Loop.ScriptReader; import info.nightscout.androidaps.plugins.Loop.ScriptReader;
import info.nightscout.androidaps.data.IobTotal; import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.client.data.NSProfile; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.utils.SP;
import info.nightscout.utils.SafeParse; import info.nightscout.utils.SafeParse;
public class DetermineBasalAdapterAMAJS { public class DetermineBasalAdapterAMAJS {
@ -209,7 +207,6 @@ public class DetermineBasalAdapterAMAJS {
double min_5m_carbimpact) { double min_5m_carbimpact) {
String units = profile.getUnits(); String units = profile.getUnits();
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext());
mProfile = new V8Object(mV8rt); mProfile = new V8Object(mV8rt);
mProfile.add("max_iob", maxIob); mProfile.add("max_iob", maxIob);
@ -222,13 +219,13 @@ public class DetermineBasalAdapterAMAJS {
mProfile.add("target_bg", targetBg); mProfile.add("target_bg", targetBg);
mProfile.add("carb_ratio", profile.getIc(profile.secondsFromMidnight())); mProfile.add("carb_ratio", profile.getIc(profile.secondsFromMidnight()));
mProfile.add("sens", NSProfile.toMgdl(profile.getIsf(NSProfile.secondsFromMidnight()).doubleValue(), units)); mProfile.add("sens", NSProfile.toMgdl(profile.getIsf(NSProfile.secondsFromMidnight()).doubleValue(), units));
mProfile.add("max_daily_safety_multiplier", SafeParse.stringToInt(preferences.getString("openapsama_max_daily_safety_multiplier", "3"))); mProfile.add("max_daily_safety_multiplier", SP.getInt("openapsama_max_daily_safety_multiplier", 3));
mProfile.add("current_basal_safety_multiplier", SafeParse.stringToInt(preferences.getString("openapsama_current_basal_safety_multiplier", "4"))); mProfile.add("current_basal_safety_multiplier", SP.getInt("openapsama_current_basal_safety_multiplier", 4));
mProfile.add("skip_neutral_temps", true); mProfile.add("skip_neutral_temps", true);
mProfile.add("current_basal", pump.getBaseBasalRate()); mProfile.add("current_basal", pump.getBaseBasalRate());
mProfile.add("temptargetSet", tempTargetSet); mProfile.add("temptargetSet", tempTargetSet);
mProfile.add("autosens_adjust_targets", preferences.getBoolean("openapsama_autosens_adjusttargets", true)); mProfile.add("autosens_adjust_targets", SP.getBoolean("openapsama_autosens_adjusttargets", true));
mProfile.add("min_5m_carbimpact", SafeParse.stringToDouble(preferences.getString("openapsama_min_5m_carbimpact", "3.0"))); mProfile.add("min_5m_carbimpact", SP.getDouble("openapsama_min_5m_carbimpact", 3d));
mV8rt.add(PARAM_profile, mProfile); mV8rt.add(PARAM_profile, mProfile);
mCurrentTemp = new V8Object(mV8rt); mCurrentTemp = new V8Object(mV8rt);

View file

@ -22,17 +22,17 @@ import info.nightscout.androidaps.db.TempTarget;
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.PumpInterface; import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.interfaces.TempBasalsInterface;
import info.nightscout.androidaps.plugins.Loop.APSResult; import info.nightscout.androidaps.plugins.Loop.APSResult;
import info.nightscout.androidaps.plugins.Loop.ScriptReader; import info.nightscout.androidaps.plugins.Loop.ScriptReader;
import info.nightscout.androidaps.data.IobTotal; import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateGui; import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateGui;
import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateResultGui; import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateResultGui;
import info.nightscout.androidaps.plugins.TempTargetRange.TempTargetRangePlugin; import info.nightscout.androidaps.plugins.TempTargetRange.TempTargetRangePlugin;
import info.nightscout.client.data.NSProfile; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.utils.DateUtil; import info.nightscout.utils.DateUtil;
import info.nightscout.utils.Profiler; import info.nightscout.utils.Profiler;
import info.nightscout.utils.Round; import info.nightscout.utils.Round;
import info.nightscout.utils.SP;
import info.nightscout.utils.SafeParse; import info.nightscout.utils.SafeParse;
import info.nightscout.utils.ToastUtils; import info.nightscout.utils.ToastUtils;
@ -156,12 +156,11 @@ public class OpenAPSAMAPlugin implements PluginBase, APSInterface {
return; return;
} }
SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext());
String units = profile.getUnits(); String units = profile.getUnits();
String maxBgDefault = Constants.MAX_BG_DEFAULT_MGDL; Double maxBgDefault = Constants.MAX_BG_DEFAULT_MGDL;
String minBgDefault = Constants.MIN_BG_DEFAULT_MGDL; Double minBgDefault = Constants.MIN_BG_DEFAULT_MGDL;
String targetBgDefault = Constants.TARGET_BG_DEFAULT_MGDL; Double targetBgDefault = Constants.TARGET_BG_DEFAULT_MGDL;
if (!units.equals(Constants.MGDL)) { if (!units.equals(Constants.MGDL)) {
maxBgDefault = Constants.MAX_BG_DEFAULT_MMOL; maxBgDefault = Constants.MAX_BG_DEFAULT_MMOL;
minBgDefault = Constants.MIN_BG_DEFAULT_MMOL; minBgDefault = Constants.MIN_BG_DEFAULT_MMOL;
@ -170,11 +169,11 @@ public class OpenAPSAMAPlugin implements PluginBase, APSInterface {
Date now = new Date(); Date now = new Date();
double maxIob = SafeParse.stringToDouble(SP.getString("openapsma_max_iob", "1.5")); double maxIob = SP.getDouble("openapsma_max_iob", 1.5d);
double maxBasal = SafeParse.stringToDouble(SP.getString("openapsma_max_basal", "1")); double maxBasal = SP.getDouble("openapsma_max_basal", 1d);
double minBg = NSProfile.toMgdl(SafeParse.stringToDouble(SP.getString("openapsma_min_bg", minBgDefault)), units); double minBg = NSProfile.toMgdl(SP.getDouble("openapsma_min_bg", minBgDefault), units);
double maxBg = NSProfile.toMgdl(SafeParse.stringToDouble(SP.getString("openapsma_max_bg", maxBgDefault)), units); double maxBg = NSProfile.toMgdl(SP.getDouble("openapsma_max_bg", maxBgDefault), units);
double targetBg = NSProfile.toMgdl(SafeParse.stringToDouble(SP.getString("openapsma_target_bg", targetBgDefault)), units); double targetBg = NSProfile.toMgdl(SP.getDouble("openapsma_target_bg", targetBgDefault), units);
minBg = Round.roundTo(minBg, 0.1d); minBg = Round.roundTo(minBg, 0.1d);
maxBg = Round.roundTo(maxBg, 0.1d); maxBg = Round.roundTo(maxBg, 0.1d);

View file

@ -18,7 +18,7 @@ import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.data.MealData; import info.nightscout.androidaps.data.MealData;
import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.plugins.Loop.ScriptReader; import info.nightscout.androidaps.plugins.Loop.ScriptReader;
import info.nightscout.client.data.NSProfile; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
public class DetermineBasalAdapterMAJS { public class DetermineBasalAdapterMAJS {
private static Logger log = LoggerFactory.getLogger(DetermineBasalAdapterMAJS.class); private static Logger log = LoggerFactory.getLogger(DetermineBasalAdapterMAJS.class);

View file

@ -1,8 +1,5 @@
package info.nightscout.androidaps.plugins.OpenAPSMA; package info.nightscout.androidaps.plugins.OpenAPSMA;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import org.json.JSONException; import org.json.JSONException;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -25,15 +22,15 @@ import info.nightscout.androidaps.interfaces.TempBasalsInterface;
import info.nightscout.androidaps.interfaces.TreatmentsInterface; import info.nightscout.androidaps.interfaces.TreatmentsInterface;
import info.nightscout.androidaps.plugins.Loop.APSResult; import info.nightscout.androidaps.plugins.Loop.APSResult;
import info.nightscout.androidaps.plugins.Loop.ScriptReader; import info.nightscout.androidaps.plugins.Loop.ScriptReader;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateGui; import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateGui;
import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateResultGui; import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateResultGui;
import info.nightscout.androidaps.plugins.TempTargetRange.TempTargetRangePlugin; import info.nightscout.androidaps.plugins.TempTargetRange.TempTargetRangePlugin;
import info.nightscout.client.data.NSProfile;
import info.nightscout.utils.DateUtil; import info.nightscout.utils.DateUtil;
import info.nightscout.utils.Profiler; import info.nightscout.utils.Profiler;
import info.nightscout.utils.Round; import info.nightscout.utils.Round;
import info.nightscout.utils.SP;
import info.nightscout.utils.SafeParse; import info.nightscout.utils.SafeParse;
import info.nightscout.utils.ToastUtils;
import static info.nightscout.androidaps.plugins.OpenAPSAMA.OpenAPSAMAPlugin.checkOnlyHardLimits; import static info.nightscout.androidaps.plugins.OpenAPSAMA.OpenAPSAMAPlugin.checkOnlyHardLimits;
import static info.nightscout.androidaps.plugins.OpenAPSAMA.OpenAPSAMAPlugin.verifyHardLimits; import static info.nightscout.androidaps.plugins.OpenAPSAMA.OpenAPSAMAPlugin.verifyHardLimits;
@ -157,12 +154,11 @@ public class OpenAPSMAPlugin implements PluginBase, APSInterface {
return; return;
} }
SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext());
String units = profile.getUnits(); String units = profile.getUnits();
String maxBgDefault = Constants.MAX_BG_DEFAULT_MGDL; Double maxBgDefault = Constants.MAX_BG_DEFAULT_MGDL;
String minBgDefault = Constants.MIN_BG_DEFAULT_MGDL; Double minBgDefault = Constants.MIN_BG_DEFAULT_MGDL;
String targetBgDefault = Constants.TARGET_BG_DEFAULT_MGDL; Double targetBgDefault = Constants.TARGET_BG_DEFAULT_MGDL;
if (!units.equals(Constants.MGDL)) { if (!units.equals(Constants.MGDL)) {
maxBgDefault = Constants.MAX_BG_DEFAULT_MMOL; maxBgDefault = Constants.MAX_BG_DEFAULT_MMOL;
minBgDefault = Constants.MIN_BG_DEFAULT_MMOL; minBgDefault = Constants.MIN_BG_DEFAULT_MMOL;
@ -171,11 +167,11 @@ public class OpenAPSMAPlugin implements PluginBase, APSInterface {
Date now = new Date(); Date now = new Date();
double maxIob = SafeParse.stringToDouble(SP.getString("openapsma_max_iob", "1.5")); double maxIob = SP.getDouble("openapsma_max_iob", 1.5d);
double maxBasal = SafeParse.stringToDouble(SP.getString("openapsma_max_basal", "1")); double maxBasal = SafeParse.stringToDouble(SP.getString("openapsma_max_basal", "1"));
double minBg = NSProfile.toMgdl(SafeParse.stringToDouble(SP.getString("openapsma_min_bg", minBgDefault)), units); double minBg = NSProfile.toMgdl(SP.getDouble("openapsma_min_bg", minBgDefault), units);
double maxBg = NSProfile.toMgdl(SafeParse.stringToDouble(SP.getString("openapsma_max_bg", maxBgDefault)), units); double maxBg = NSProfile.toMgdl(SP.getDouble("openapsma_max_bg", maxBgDefault), units);
double targetBg = NSProfile.toMgdl(SafeParse.stringToDouble(SP.getString("openapsma_target_bg", targetBgDefault)), units); double targetBg = NSProfile.toMgdl(SP.getDouble("openapsma_target_bg", targetBgDefault), units);
minBg = Round.roundTo(minBg, 0.1d); minBg = Round.roundTo(minBg, 0.1d);
maxBg = Round.roundTo(maxBg, 0.1d); maxBg = Round.roundTo(maxBg, 0.1d);

View file

@ -18,10 +18,10 @@ 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.events.EventPumpStatusChanged;
import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.plugins.Overview.events.EventOverviewBolusProgress; import info.nightscout.androidaps.plugins.Overview.events.EventOverviewBolusProgress;
import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRBolusStart; import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRBolusStart;
import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRConnectionStatus;
public class BolusProgressDialog extends DialogFragment implements View.OnClickListener { public class BolusProgressDialog extends DialogFragment implements View.OnClickListener {
private static Logger log = LoggerFactory.getLogger(BolusProgressDialog.class); private static Logger log = LoggerFactory.getLogger(BolusProgressDialog.class);
@ -46,7 +46,7 @@ public class BolusProgressDialog extends DialogFragment implements View.OnClickL
bolusEnded = false; bolusEnded = false;
} }
public void setHelperActivity(BolusProgressHelperActivity activity){ public void setHelperActivity(BolusProgressHelperActivity activity) {
this.helperActivity = activity; this.helperActivity = activity;
} }
@ -77,9 +77,9 @@ public class BolusProgressDialog extends DialogFragment implements View.OnClickL
} }
@Override @Override
public void dismiss(){ public void dismiss() {
super.dismiss(); super.dismiss();
if (helperActivity!= null){ if (helperActivity != null) {
helperActivity.finish(); helperActivity.finish();
} }
} }
@ -128,7 +128,7 @@ public class BolusProgressDialog extends DialogFragment implements View.OnClickL
} }
@Subscribe @Subscribe
public void onStatusEvent(final EventDanaRConnectionStatus c) { public void onStatusEvent(final EventPumpStatusChanged c) {
Activity activity = getActivity(); Activity activity = getActivity();
if (activity != null) { if (activity != null) {
@ -136,14 +136,7 @@ public class BolusProgressDialog extends DialogFragment implements View.OnClickL
new Runnable() { new Runnable() {
@Override @Override
public void run() { public void run() {
if (c.sStatus == c.CONNECTING) { statusView.setText(c.textStatus());
statusView.setText(String.format(MainApp.sResources.getString(R.string.danar_history_connectingfor), c.sSecondsElapsed));
} else if (c.sStatus == c.CONNECTED) {
statusView.setText(MainApp.sResources.getString(R.string.connected));
} else {
statusView.setText(MainApp.sResources.getString(R.string.disconnected));
if (started) scheduleDismiss();
}
} }
} }
); );

View file

@ -21,7 +21,7 @@ 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.GlucoseStatus; import info.nightscout.androidaps.data.GlucoseStatus;
import info.nightscout.client.data.NSProfile; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.utils.PlusMinusEditText; import info.nightscout.utils.PlusMinusEditText;
import info.nightscout.utils.XdripCalibrations; import info.nightscout.utils.XdripCalibrations;

View file

@ -43,7 +43,7 @@ import info.nightscout.androidaps.interfaces.TempBasalsInterface;
import info.nightscout.androidaps.interfaces.TreatmentsInterface; import info.nightscout.androidaps.interfaces.TreatmentsInterface;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.data.IobTotal; import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.client.data.NSProfile; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.utils.BolusWizard; import info.nightscout.utils.BolusWizard;
import info.nightscout.utils.DateUtil; import info.nightscout.utils.DateUtil;
import info.nightscout.utils.DecimalFormatter; import info.nightscout.utils.DecimalFormatter;

View file

@ -23,6 +23,7 @@ public class Notification {
public static final int OLD_NSCLIENT = 8; public static final int OLD_NSCLIENT = 8;
public static final int INVALID_PHONE_NUMBER = 9; public static final int INVALID_PHONE_NUMBER = 9;
public static final int APPROACHING_DAILY_LIMIT = 10; public static final int APPROACHING_DAILY_LIMIT = 10;
public static final int NSCLIENT_NO_WRITE_PERMISSION = 10;
public int id; public int id;
public Date date; public Date date;

View file

@ -63,6 +63,7 @@ import info.nightscout.androidaps.events.EventInitializationChanged;
import info.nightscout.androidaps.events.EventNewBG; import info.nightscout.androidaps.events.EventNewBG;
import info.nightscout.androidaps.events.EventNewBasalProfile; import info.nightscout.androidaps.events.EventNewBasalProfile;
import info.nightscout.androidaps.events.EventPreferenceChange; import info.nightscout.androidaps.events.EventPreferenceChange;
import info.nightscout.androidaps.events.EventPumpStatusChanged;
import info.nightscout.androidaps.events.EventRefreshGui; import info.nightscout.androidaps.events.EventRefreshGui;
import info.nightscout.androidaps.events.EventTempBasalChange; import info.nightscout.androidaps.events.EventTempBasalChange;
import info.nightscout.androidaps.events.EventTreatmentChange; import info.nightscout.androidaps.events.EventTreatmentChange;
@ -71,7 +72,6 @@ import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.plugins.Careportal.Dialogs.NewNSTreatmentDialog; import info.nightscout.androidaps.plugins.Careportal.Dialogs.NewNSTreatmentDialog;
import info.nightscout.androidaps.plugins.Careportal.OptionsToShow; import info.nightscout.androidaps.plugins.Careportal.OptionsToShow;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.DanaR.events.EventDanaRConnectionStatus;
import info.nightscout.androidaps.plugins.Loop.LoopPlugin; import info.nightscout.androidaps.plugins.Loop.LoopPlugin;
import info.nightscout.androidaps.plugins.Loop.events.EventNewOpenLoopNotification; import info.nightscout.androidaps.plugins.Loop.events.EventNewOpenLoopNotification;
import info.nightscout.androidaps.plugins.Objectives.ObjectivesPlugin; import info.nightscout.androidaps.plugins.Objectives.ObjectivesPlugin;
@ -87,19 +87,18 @@ import info.nightscout.androidaps.plugins.Overview.graphExtensions.TimeAsXAxisLa
import info.nightscout.androidaps.plugins.SourceXdrip.SourceXdripPlugin; import info.nightscout.androidaps.plugins.SourceXdrip.SourceXdripPlugin;
import info.nightscout.androidaps.plugins.TempTargetRange.TempTargetRangePlugin; import info.nightscout.androidaps.plugins.TempTargetRange.TempTargetRangePlugin;
import info.nightscout.androidaps.plugins.TempTargetRange.events.EventTempTargetRangeChange; import info.nightscout.androidaps.plugins.TempTargetRange.events.EventTempTargetRangeChange;
import info.nightscout.client.data.NSProfile; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.utils.BolusWizard; import info.nightscout.utils.BolusWizard;
import info.nightscout.utils.DateUtil; import info.nightscout.utils.DateUtil;
import info.nightscout.utils.DecimalFormatter; import info.nightscout.utils.DecimalFormatter;
import info.nightscout.utils.Round; import info.nightscout.utils.Round;
import info.nightscout.utils.SafeParse; import info.nightscout.utils.SP;
public class OverviewFragment extends Fragment { public class OverviewFragment extends Fragment {
private static Logger log = LoggerFactory.getLogger(OverviewFragment.class); private static Logger log = LoggerFactory.getLogger(OverviewFragment.class);
private static OverviewPlugin overviewPlugin = new OverviewPlugin(); private static OverviewPlugin overviewPlugin = new OverviewPlugin();
private SharedPreferences prefs;
public static OverviewPlugin getPlugin() { public static OverviewPlugin getPlugin() {
return overviewPlugin; return overviewPlugin;
@ -118,6 +117,8 @@ public class OverviewFragment extends Fragment {
TextView apsModeView; TextView apsModeView;
TextView tempTargetView; TextView tempTargetView;
TextView pumpStatusView; TextView pumpStatusView;
LinearLayout loopStatusLayout;
LinearLayout pumpStatusLayout;
GraphView bgGraph; GraphView bgGraph;
CheckBox showPredictionView; CheckBox showPredictionView;
@ -151,7 +152,6 @@ public class OverviewFragment extends Fragment {
@Override @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) { Bundle savedInstanceState) {
prefs = PreferenceManager.getDefaultSharedPreferences(getContext());
View view = inflater.inflate(R.layout.overview_fragment, container, false); View view = inflater.inflate(R.layout.overview_fragment, container, false);
bgView = (TextView) view.findViewById(R.id.overview_bg); bgView = (TextView) view.findViewById(R.id.overview_bg);
@ -163,7 +163,9 @@ public class OverviewFragment extends Fragment {
baseBasalView = (TextView) view.findViewById(R.id.overview_basebasal); baseBasalView = (TextView) view.findViewById(R.id.overview_basebasal);
basalLayout = (LinearLayout) view.findViewById(R.id.overview_basallayout); basalLayout = (LinearLayout) view.findViewById(R.id.overview_basallayout);
activeProfileView = (TextView) view.findViewById(R.id.overview_activeprofile); activeProfileView = (TextView) view.findViewById(R.id.overview_activeprofile);
pumpStatusView = (TextView) view.findViewById(R.id.overview_initializing); pumpStatusView = (TextView) view.findViewById(R.id.overview_pumpstatus);
loopStatusLayout = (LinearLayout) view.findViewById(R.id.overview_looplayout);
pumpStatusLayout = (LinearLayout) view.findViewById(R.id.overview_pumpstatuslayout);
iobView = (TextView) view.findViewById(R.id.overview_iob); iobView = (TextView) view.findViewById(R.id.overview_iob);
apsModeView = (TextView) view.findViewById(R.id.overview_apsmode); apsModeView = (TextView) view.findViewById(R.id.overview_apsmode);
@ -185,12 +187,13 @@ public class OverviewFragment extends Fragment {
llm = new LinearLayoutManager(view.getContext()); llm = new LinearLayoutManager(view.getContext());
notificationsView.setLayoutManager(llm); notificationsView.setLayoutManager(llm);
showPredictionView.setChecked(prefs.getBoolean("showprediction", false)); showPredictionView.setChecked(SP.getBoolean("showprediction", false));
showPredictionView.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { showPredictionView.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override @Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
SharedPreferences.Editor editor = prefs.edit(); SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext());
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("showprediction", showPredictionView.isChecked()); editor.putBoolean("showprediction", showPredictionView.isChecked());
editor.apply(); editor.apply();
updateGUI(); updateGUI();
@ -295,7 +298,7 @@ public class OverviewFragment extends Fragment {
sHandler.post(new Runnable() { sHandler.post(new Runnable() {
@Override @Override
public void run() { public void run() {
MainApp.getConfigBuilder().updateStatus("RefreshClicked"); MainApp.getConfigBuilder().refreshDataFromPump("RefreshClicked");
} }
}); });
} }
@ -477,18 +480,13 @@ public class OverviewFragment extends Fragment {
} }
@Subscribe @Subscribe
public void onStatusEvent(final EventDanaRConnectionStatus s) { public void onStatusEvent(final EventPumpStatusChanged s) {
Activity activity = getActivity(); Activity activity = getActivity();
if (activity != null) if (activity != null)
activity.runOnUiThread(new Runnable() { activity.runOnUiThread(new Runnable() {
@Override @Override
public void run() { public void run() {
if (s.sStatus == EventDanaRConnectionStatus.CONNECTING) updatePumpStatus(s.textStatus());
updatePumpStatus(String.format(getString(R.string.danar_history_connectingfor), s.sSecondsElapsed));
else if (s.sStatus == EventDanaRConnectionStatus.PERFORMING)
updatePumpStatus(s.sAction);
else if (s.sStatus == EventDanaRConnectionStatus.DISCONNECTED)
updatePumpStatus(null);
} }
}); });
} }
@ -517,30 +515,15 @@ public class OverviewFragment extends Fragment {
private void updatePumpStatus(String status) { private void updatePumpStatus(String status) {
PumpInterface pump = MainApp.getConfigBuilder(); PumpInterface pump = MainApp.getConfigBuilder();
if (status != null) { if (!status.equals("")) {
pumpStatusView.setText(status); pumpStatusView.setText(status);
pumpStatusView.setVisibility(View.VISIBLE); pumpStatusLayout.setVisibility(View.VISIBLE);
} else if (pump.isBusy()) { loopStatusLayout.setVisibility(View.GONE);
pumpStatusView.setText(R.string.pumpbusy);
pumpStatusView.setVisibility(View.VISIBLE);
} else if (pump.isSuspended()) {
// disable all treatment buttons because we are not able to check constraints without profile
wizardButton.setVisibility(View.INVISIBLE);
treatmentButton.setVisibility(View.INVISIBLE);
quickWizardButton.setVisibility(View.INVISIBLE);
pumpStatusView.setText(R.string.pumpsuspendedclicktorefresh);
pumpStatusView.setVisibility(View.VISIBLE);
} else if (!pump.isInitialized()) {
// disable all treatment buttons because we are not able to check constraints without profile
wizardButton.setVisibility(View.INVISIBLE);
treatmentButton.setVisibility(View.INVISIBLE);
quickWizardButton.setVisibility(View.INVISIBLE);
pumpStatusView.setText(R.string.waitingforpumpclicktorefresh);
pumpStatusView.setVisibility(View.VISIBLE);
} else { } else {
wizardButton.setVisibility(View.VISIBLE); wizardButton.setVisibility(View.VISIBLE);
treatmentButton.setVisibility(View.VISIBLE); treatmentButton.setVisibility(View.VISIBLE);
pumpStatusView.setVisibility(View.GONE); pumpStatusLayout.setVisibility(View.GONE);
loopStatusLayout.setVisibility(View.VISIBLE);
} }
} }
@ -552,10 +535,12 @@ public class OverviewFragment extends Fragment {
if (MainApp.getConfigBuilder() == null || MainApp.getConfigBuilder().getActiveProfile() == null || MainApp.getConfigBuilder().getActiveProfile().getProfile() == null) {// app not initialized yet if (MainApp.getConfigBuilder() == null || MainApp.getConfigBuilder().getActiveProfile() == null || MainApp.getConfigBuilder().getActiveProfile().getProfile() == null) {// app not initialized yet
pumpStatusView.setText(R.string.noprofileset); pumpStatusView.setText(R.string.noprofileset);
pumpStatusView.setVisibility(View.VISIBLE); pumpStatusLayout.setVisibility(View.VISIBLE);
loopStatusLayout.setVisibility(View.GONE);
return; return;
} else { } else {
pumpStatusView.setVisibility(View.GONE); pumpStatusLayout.setVisibility(View.GONE);
loopStatusLayout.setVisibility(View.VISIBLE);
} }
// Skip if not initialized yet // Skip if not initialized yet
@ -623,15 +608,15 @@ public class OverviewFragment extends Fragment {
tempTargetView.setText(NSProfile.toUnitsString(tempTarget.low, NSProfile.fromMgdlToUnits(tempTarget.low, profile.getUnits()), profile.getUnits()) + " - " + NSProfile.toUnitsString(tempTarget.high, NSProfile.fromMgdlToUnits(tempTarget.high, profile.getUnits()), profile.getUnits())); tempTargetView.setText(NSProfile.toUnitsString(tempTarget.low, NSProfile.fromMgdlToUnits(tempTarget.low, profile.getUnits()), profile.getUnits()) + " - " + NSProfile.toUnitsString(tempTarget.high, NSProfile.fromMgdlToUnits(tempTarget.high, profile.getUnits()), profile.getUnits()));
} else { } else {
String maxBgDefault = Constants.MAX_BG_DEFAULT_MGDL; Double maxBgDefault = Constants.MAX_BG_DEFAULT_MGDL;
String minBgDefault = Constants.MIN_BG_DEFAULT_MGDL; Double minBgDefault = Constants.MIN_BG_DEFAULT_MGDL;
if (!profile.getUnits().equals(Constants.MGDL)) { if (!profile.getUnits().equals(Constants.MGDL)) {
maxBgDefault = Constants.MAX_BG_DEFAULT_MMOL; maxBgDefault = Constants.MAX_BG_DEFAULT_MMOL;
minBgDefault = Constants.MIN_BG_DEFAULT_MMOL; minBgDefault = Constants.MIN_BG_DEFAULT_MMOL;
} }
tempTargetView.setTextColor(Color.WHITE); tempTargetView.setTextColor(Color.WHITE);
tempTargetView.setBackgroundResource(R.drawable.temptargetborderdisabled); tempTargetView.setBackgroundResource(R.drawable.temptargetborderdisabled);
tempTargetView.setText(prefs.getString("openapsma_min_bg", minBgDefault) + " - " + prefs.getString("openapsma_max_bg", maxBgDefault)); tempTargetView.setText(SP.getDouble("openapsma_min_bg", minBgDefault) + " - " + SP.getDouble("openapsma_max_bg", maxBgDefault));
tempTargetView.setVisibility(View.VISIBLE); tempTargetView.setVisibility(View.VISIBLE);
} }
} else { } else {
@ -799,8 +784,8 @@ public class OverviewFragment extends Fragment {
endTime = toTime; endTime = toTime;
} }
Double lowLine = SafeParse.stringToDouble(prefs.getString("low_mark", "0")); Double lowLine = SP.getDouble("low_mark", 0d);
Double highLine = SafeParse.stringToDouble(prefs.getString("high_mark", "0")); Double highLine = SP.getDouble("high_mark", 0d);
if (lowLine < 1) { if (lowLine < 1) {
lowLine = NSProfile.fromMgdlToUnits(OverviewPlugin.bgTargetLow, units); lowLine = NSProfile.fromMgdlToUnits(OverviewPlugin.bgTargetLow, units);
@ -1003,7 +988,7 @@ public class OverviewFragment extends Fragment {
bgGraph.getGridLabelRenderer().setVerticalLabelsSecondScaleColor(ContextCompat.getColor(MainApp.instance(), R.color.background_material_dark)); // same color as backround = hide bgGraph.getGridLabelRenderer().setVerticalLabelsSecondScaleColor(ContextCompat.getColor(MainApp.instance(), R.color.background_material_dark)); // same color as backround = hide
} }
updatePumpStatus(null); //updatePumpStatus(null);
} }
//Notifications //Notifications

View file

@ -1,8 +1,5 @@
package info.nightscout.androidaps.plugins.Overview; package info.nightscout.androidaps.plugins.Overview;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import com.squareup.otto.Subscribe; import com.squareup.otto.Subscribe;
import org.json.JSONArray; import org.json.JSONArray;
@ -13,6 +10,7 @@ import info.nightscout.androidaps.R;
import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification; import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification;
import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification; import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification;
import info.nightscout.utils.SP;
/** /**
* Created by mike on 05.08.2016. * Created by mike on 05.08.2016.
@ -27,8 +25,7 @@ public class OverviewPlugin implements PluginBase {
public NotificationStore notificationStore = new NotificationStore(); public NotificationStore notificationStore = new NotificationStore();
public OverviewPlugin() { public OverviewPlugin() {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext()); String storedData = SP.getString("QuickWizard", "[]");
String storedData = preferences.getString("QuickWizard", "[]");
try { try {
quickWizard.setData(new JSONArray(storedData)); quickWizard.setData(new JSONArray(storedData));
} catch (JSONException e) { } catch (JSONException e) {

View file

@ -7,12 +7,10 @@ import org.json.JSONArray;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import java.util.Calendar;
import java.util.Date; import java.util.Date;
import java.util.GregorianCalendar;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.client.data.NSProfile; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.utils.DateUtil; import info.nightscout.utils.DateUtil;
/** /**

View file

@ -1,8 +1,5 @@
package info.nightscout.androidaps.plugins.SafetyFragment; package info.nightscout.androidaps.plugins.SafetyFragment;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -13,9 +10,9 @@ import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.interfaces.ConstraintsInterface; import info.nightscout.androidaps.interfaces.ConstraintsInterface;
import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.client.data.NSProfile; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.utils.Round; import info.nightscout.utils.Round;
import info.nightscout.utils.SafeParse; import info.nightscout.utils.SP;
/** /**
* Created by mike on 05.08.2016. * Created by mike on 05.08.2016.
@ -78,7 +75,6 @@ public class SafetyPlugin implements PluginBase, ConstraintsInterface {
**/ **/
@Override @Override
public boolean isClosedModeEnabled() { public boolean isClosedModeEnabled() {
SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext());
String mode = SP.getString("aps_mode", "open"); String mode = SP.getString("aps_mode", "open");
return mode.equals("closed") && BuildConfig.CLOSEDLOOP; return mode.equals("closed") && BuildConfig.CLOSEDLOOP;
} }
@ -96,15 +92,14 @@ public class SafetyPlugin implements PluginBase, ConstraintsInterface {
@Override @Override
public Double applyBasalConstraints(Double absoluteRate) { public Double applyBasalConstraints(Double absoluteRate) {
Double origAbsoluteRate = absoluteRate; Double origAbsoluteRate = absoluteRate;
SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext()); Double maxBasal = SP.getDouble("openapsma_max_basal", 1d);
Double maxBasal = SafeParse.stringToDouble(SP.getString("openapsma_max_basal", "1"));
NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile(); NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile();
if (profile == null) return absoluteRate; if (profile == null) return absoluteRate;
if (absoluteRate < 0) absoluteRate = 0d; if (absoluteRate < 0) absoluteRate = 0d;
Integer maxBasalMult = SafeParse.stringToInt(SP.getString("openapsama_current_basal_safety_multiplier", "4")); Integer maxBasalMult = SP.getInt("openapsama_current_basal_safety_multiplier", 4);
Integer maxBasalFromDaily = SafeParse.stringToInt(SP.getString("openapsama_max_daily_safety_multiplier", "3")); Integer maxBasalFromDaily = SP.getInt("openapsama_max_daily_safety_multiplier", 3);
// Check percentRate but absolute rate too, because we know real current basal in pump // Check percentRate but absolute rate too, because we know real current basal in pump
Double origRate = absoluteRate; Double origRate = absoluteRate;
if (absoluteRate > maxBasal) { if (absoluteRate > maxBasal) {
@ -128,8 +123,7 @@ public class SafetyPlugin implements PluginBase, ConstraintsInterface {
@Override @Override
public Integer applyBasalConstraints(Integer percentRate) { public Integer applyBasalConstraints(Integer percentRate) {
Integer origPercentRate = percentRate; Integer origPercentRate = percentRate;
SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext()); Double maxBasal = SP.getDouble("openapsma_max_basal", 1d);
Double maxBasal = SafeParse.stringToDouble(SP.getString("openapsma_max_basal", "1"));
NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile(); NSProfile profile = MainApp.getConfigBuilder().getActiveProfile().getProfile();
if (profile == null) return percentRate; if (profile == null) return percentRate;
@ -142,8 +136,8 @@ public class SafetyPlugin implements PluginBase, ConstraintsInterface {
if (absoluteRate < 0) absoluteRate = 0d; if (absoluteRate < 0) absoluteRate = 0d;
Integer maxBasalMult = SafeParse.stringToInt(SP.getString("openapsama_current_basal_safety_multiplier", "4")); Integer maxBasalMult = SP.getInt("openapsama_current_basal_safety_multiplier", 4);
Integer maxBasalFromDaily = SafeParse.stringToInt(SP.getString("openapsama_max_daily_safety_multiplier", "3")); Integer maxBasalFromDaily = SP.getInt("openapsama_max_daily_safety_multiplier", 3);
// Check percentRate but absolute rate too, because we know real current basal in pump // Check percentRate but absolute rate too, because we know real current basal in pump
Double origRate = absoluteRate; Double origRate = absoluteRate;
if (absoluteRate > maxBasal) { if (absoluteRate > maxBasal) {
@ -174,9 +168,8 @@ public class SafetyPlugin implements PluginBase, ConstraintsInterface {
@Override @Override
public Double applyBolusConstraints(Double insulin) { public Double applyBolusConstraints(Double insulin) {
SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext());
try { try {
Double maxBolus = SafeParse.stringToDouble(SP.getString("treatmentssafety_maxbolus", "3")); Double maxBolus = SP.getDouble("treatmentssafety_maxbolus", 3d);
if (insulin < 0) insulin = 0d; if (insulin < 0) insulin = 0d;
if (insulin > maxBolus) insulin = maxBolus; if (insulin > maxBolus) insulin = maxBolus;
@ -189,9 +182,8 @@ public class SafetyPlugin implements PluginBase, ConstraintsInterface {
@Override @Override
public Integer applyCarbsConstraints(Integer carbs) { public Integer applyCarbsConstraints(Integer carbs) {
SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext());
try { try {
Integer maxCarbs = SafeParse.stringToInt(SP.getString("treatmentssafety_maxcarbs", "48")); Integer maxCarbs = SP.getInt("treatmentssafety_maxcarbs", 48);
if (carbs < 0) carbs = 0; if (carbs < 0) carbs = 0;
if (carbs > maxCarbs) carbs = maxCarbs; if (carbs > maxCarbs) carbs = maxCarbs;

View file

@ -15,7 +15,8 @@ import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.ProfileInterface; import info.nightscout.androidaps.interfaces.ProfileInterface;
import info.nightscout.client.data.NSProfile; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.utils.SP;
import info.nightscout.utils.SafeParse; import info.nightscout.utils.SafeParse;
/** /**
@ -60,7 +61,7 @@ public class SimpleProfilePlugin implements PluginBase, ProfileInterface {
@Override @Override
public String getNameShort() { public String getNameShort() {
String name = MainApp.sResources.getString(R.string.simpleprofile_shortname); String name = MainApp.sResources.getString(R.string.simpleprofile_shortname);
if (!name.trim().isEmpty()){ if (!name.trim().isEmpty()) {
//only if translation exists //only if translation exists
return name; return name;
} }
@ -114,64 +115,15 @@ public class SimpleProfilePlugin implements PluginBase, ProfileInterface {
private void loadSettings() { private void loadSettings() {
if (Config.logPrefsChange) if (Config.logPrefsChange)
log.debug("Loading stored settings"); log.debug("Loading stored settings");
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext());
if (settings.contains("SimpleProfile" + "mgdl")) mgdl = SP.getBoolean("SimpleProfile" + "mgdl", true);
try { mmol = SP.getBoolean("SimpleProfile" + "mmol", false);
mgdl = settings.getBoolean("SimpleProfile" + "mgdl", true); dia = SP.getDouble("SimpleProfile" + "dia", 3d);
} catch (Exception e) { ic = SP.getDouble("SimpleProfile" + "ic", 20d);
log.debug(e.getMessage()); isf = SP.getDouble("SimpleProfile" + "isf", 200d);
} basal = SP.getDouble("SimpleProfile" + "basal", 1d);
else mgdl = true; targetLow = SP.getDouble("SimpleProfile" + "targetlow", 80d);
if (settings.contains("SimpleProfile" + "mmol")) targetHigh = SP.getDouble("SimpleProfile" + "targethigh", 120d);
try {
mmol = settings.getBoolean("SimpleProfile" + "mmol", false);
} catch (Exception e) {
log.debug(e.getMessage());
}
else mmol = false;
if (settings.contains("SimpleProfile" + "dia"))
try {
dia = SafeParse.stringToDouble(settings.getString("SimpleProfile" + "dia", "3"));
} catch (Exception e) {
log.debug(e.getMessage());
}
else dia = 3d;
if (settings.contains("SimpleProfile" + "ic"))
try {
ic = SafeParse.stringToDouble(settings.getString("SimpleProfile" + "ic", "20"));
} catch (Exception e) {
log.debug(e.getMessage());
}
else ic = 20d;
if (settings.contains("SimpleProfile" + "isf"))
try {
isf = SafeParse.stringToDouble(settings.getString("SimpleProfile" + "isf", "200"));
} catch (Exception e) {
log.debug(e.getMessage());
}
else isf = 200d;
if (settings.contains("SimpleProfile" + "basal"))
try {
basal = SafeParse.stringToDouble(settings.getString("SimpleProfile" + "basal", "1"));
} catch (Exception e) {
log.debug(e.getMessage());
}
else basal = 1d;
if (settings.contains("SimpleProfile" + "targetlow"))
try {
targetLow = SafeParse.stringToDouble(settings.getString("SimpleProfile" + "targetlow", "80"));
} catch (Exception e) {
log.debug(e.getMessage());
}
else targetLow = 80d;
if (settings.contains("SimpleProfile" + "targethigh"))
try {
targetHigh = SafeParse.stringToDouble(settings.getString("SimpleProfile" + "targethigh", "120"));
} catch (Exception e) {
log.debug(e.getMessage());
}
else targetHigh = 120d;
createConvertedProfile(); createConvertedProfile();
} }

View file

@ -22,6 +22,7 @@ import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.Services.Intents; import info.nightscout.androidaps.Services.Intents;
import info.nightscout.androidaps.data.GlucoseStatus; import info.nightscout.androidaps.data.GlucoseStatus;
import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.data.PumpEnactResult; import info.nightscout.androidaps.data.PumpEnactResult;
import info.nightscout.androidaps.db.BgReading; import info.nightscout.androidaps.db.BgReading;
import info.nightscout.androidaps.events.EventPreferenceChange; import info.nightscout.androidaps.events.EventPreferenceChange;
@ -30,13 +31,13 @@ import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.plugins.DanaR.DanaRPlugin; import info.nightscout.androidaps.plugins.DanaR.DanaRPlugin;
import info.nightscout.androidaps.plugins.DanaRKorean.DanaRKoreanPlugin; import info.nightscout.androidaps.plugins.DanaRKorean.DanaRKoreanPlugin;
import info.nightscout.androidaps.plugins.Loop.LoopPlugin; import info.nightscout.androidaps.plugins.Loop.LoopPlugin;
import info.nightscout.androidaps.data.IobTotal; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.androidaps.plugins.Overview.Notification; import info.nightscout.androidaps.plugins.Overview.Notification;
import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification; import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.SmsCommunicator.events.EventNewSMS; import info.nightscout.androidaps.plugins.SmsCommunicator.events.EventNewSMS;
import info.nightscout.androidaps.plugins.SmsCommunicator.events.EventSmsCommunicatorUpdateGui; import info.nightscout.androidaps.plugins.SmsCommunicator.events.EventSmsCommunicatorUpdateGui;
import info.nightscout.client.data.NSProfile;
import info.nightscout.utils.DecimalFormatter; import info.nightscout.utils.DecimalFormatter;
import info.nightscout.utils.SP;
import info.nightscout.utils.SafeParse; import info.nightscout.utils.SafeParse;
import info.nightscout.utils.XdripCalibrations; import info.nightscout.utils.XdripCalibrations;
@ -159,8 +160,7 @@ public class SmsCommunicatorPlugin implements PluginBase {
@Subscribe @Subscribe
public void processSettings(final EventPreferenceChange ev) { public void processSettings(final EventPreferenceChange ev) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext()); String settings = SP.getString("smscommunicator_allowednumbers", "");
String settings = sharedPreferences.getString("smscommunicator_allowednumbers", "");
String pattern = ";"; String pattern = ";";
@ -191,8 +191,6 @@ public class SmsCommunicatorPlugin implements PluginBase {
} }
private void processSms(Sms receivedSms) { private void processSms(Sms receivedSms) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext());
if (!isEnabled(PluginBase.GENERAL)) { if (!isEnabled(PluginBase.GENERAL)) {
log.debug("Ignoring SMS. Plugin disabled."); log.debug("Ignoring SMS. Plugin disabled.");
return; return;
@ -319,7 +317,7 @@ public class SmsCommunicatorPlugin implements PluginBase {
break; break;
case "BASAL": case "BASAL":
if (splited.length > 1) { if (splited.length > 1) {
boolean remoteCommandsAllowed = sharedPreferences.getBoolean("smscommunicator_remotecommandsallowed", false); boolean remoteCommandsAllowed = SP.getBoolean("smscommunicator_remotecommandsallowed", false);
if (splited[1].toUpperCase().equals("CANCEL") || splited[1].toUpperCase().equals("STOP")) { if (splited[1].toUpperCase().equals("CANCEL") || splited[1].toUpperCase().equals("STOP")) {
if (remoteCommandsAllowed) { if (remoteCommandsAllowed) {
passCode = generatePasscode(); passCode = generatePasscode();
@ -355,7 +353,7 @@ public class SmsCommunicatorPlugin implements PluginBase {
} else if (splited.length > 1) { } else if (splited.length > 1) {
amount = SafeParse.stringToDouble(splited[1]); amount = SafeParse.stringToDouble(splited[1]);
amount = MainApp.getConfigBuilder().applyBolusConstraints(amount); amount = MainApp.getConfigBuilder().applyBolusConstraints(amount);
boolean remoteCommandsAllowed = sharedPreferences.getBoolean("smscommunicator_remotecommandsallowed", false); boolean remoteCommandsAllowed = SP.getBoolean("smscommunicator_remotecommandsallowed", false);
if (amount > 0d && remoteCommandsAllowed) { if (amount > 0d && remoteCommandsAllowed) {
passCode = generatePasscode(); passCode = generatePasscode();
reply = String.format(MainApp.sResources.getString(R.string.smscommunicator_bolusreplywithcode), amount, passCode); reply = String.format(MainApp.sResources.getString(R.string.smscommunicator_bolusreplywithcode), amount, passCode);
@ -372,7 +370,7 @@ public class SmsCommunicatorPlugin implements PluginBase {
case "CAL": case "CAL":
if (splited.length > 1) { if (splited.length > 1) {
amount = SafeParse.stringToDouble(splited[1]); amount = SafeParse.stringToDouble(splited[1]);
boolean remoteCommandsAllowed = sharedPreferences.getBoolean("smscommunicator_remotecommandsallowed", false); boolean remoteCommandsAllowed = SP.getBoolean("smscommunicator_remotecommandsallowed", false);
if (amount > 0d && remoteCommandsAllowed) { if (amount > 0d && remoteCommandsAllowed) {
passCode = generatePasscode(); passCode = generatePasscode();
reply = String.format(MainApp.sResources.getString(R.string.smscommunicator_calibrationreplywithcode), amount, passCode); reply = String.format(MainApp.sResources.getString(R.string.smscommunicator_calibrationreplywithcode), amount, passCode);

View file

@ -34,7 +34,7 @@ import info.nightscout.androidaps.db.TempTarget;
import info.nightscout.androidaps.interfaces.FragmentBase; import info.nightscout.androidaps.interfaces.FragmentBase;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.TempTargetRange.events.EventTempTargetRangeChange; import info.nightscout.androidaps.plugins.TempTargetRange.events.EventTempTargetRangeChange;
import info.nightscout.client.data.NSProfile; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.utils.DateUtil; import info.nightscout.utils.DateUtil;
import info.nightscout.utils.DecimalFormatter; import info.nightscout.utils.DecimalFormatter;
import info.nightscout.utils.ToastUtils; import info.nightscout.utils.ToastUtils;

View file

@ -36,7 +36,7 @@ import info.nightscout.androidaps.data.Iob;
import info.nightscout.androidaps.db.Treatment; import info.nightscout.androidaps.db.Treatment;
import info.nightscout.androidaps.events.EventTreatmentChange; import info.nightscout.androidaps.events.EventTreatmentChange;
import info.nightscout.androidaps.interfaces.FragmentBase; import info.nightscout.androidaps.interfaces.FragmentBase;
import info.nightscout.client.data.NSProfile; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.utils.DateUtil; import info.nightscout.utils.DateUtil;
import info.nightscout.utils.DecimalFormatter; import info.nightscout.utils.DecimalFormatter;
import info.nightscout.utils.ToastUtils; import info.nightscout.utils.ToastUtils;

View file

@ -1,35 +1,25 @@
package info.nightscout.androidaps.plugins.Treatments; package info.nightscout.androidaps.plugins.Treatments;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.stmt.PreparedQuery;
import com.j256.ormlite.stmt.QueryBuilder;
import com.j256.ormlite.stmt.Where;
import com.squareup.otto.Subscribe; import com.squareup.otto.Subscribe;
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.Date; import java.util.Date;
import java.util.List; import java.util.List;
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.Iob; import info.nightscout.androidaps.data.Iob;
import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.data.MealData; import info.nightscout.androidaps.data.MealData;
import info.nightscout.androidaps.db.Treatment; import info.nightscout.androidaps.db.Treatment;
import info.nightscout.androidaps.events.EventTreatmentChange; import info.nightscout.androidaps.events.EventTreatmentChange;
import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.TreatmentsInterface; import info.nightscout.androidaps.interfaces.TreatmentsInterface;
import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.client.data.NSProfile; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.utils.SafeParse; import info.nightscout.utils.SP;
/** /**
* Created by mike on 05.08.2016. * Created by mike on 05.08.2016.
@ -125,7 +115,6 @@ public class TreatmentsPlugin implements PluginBase, TreatmentsInterface {
@Override @Override
public IobTotal getCalculationToTime(long time) { public IobTotal getCalculationToTime(long time) {
SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext());
IobTotal total = new IobTotal(time); IobTotal total = new IobTotal(time);
if (MainApp.getConfigBuilder() == null || ConfigBuilderPlugin.getActiveProfile() == null) // app not initialized yet if (MainApp.getConfigBuilder() == null || ConfigBuilderPlugin.getActiveProfile() == null) // app not initialized yet
@ -143,7 +132,7 @@ public class TreatmentsPlugin implements PluginBase, TreatmentsInterface {
Iob tIOB = t.iobCalc(now, dia); Iob tIOB = t.iobCalc(now, dia);
total.iob += tIOB.iobContrib; total.iob += tIOB.iobContrib;
total.activity += tIOB.activityContrib; total.activity += tIOB.activityContrib;
Iob bIOB = t.iobCalc(now, dia / SafeParse.stringToInt(SP.getString("openapsama_bolussnooze_dia_divisor", "2"))); Iob bIOB = t.iobCalc(now, dia / SP.getInt("openapsama_bolussnooze_dia_divisor", 2));
total.bolussnooze += bIOB.iobContrib; total.bolussnooze += bIOB.iobContrib;
} }
return total; return total;

View file

@ -23,7 +23,7 @@ import info.nightscout.androidaps.interfaces.PumpDescription;
import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.plugins.Overview.events.EventOverviewBolusProgress; import info.nightscout.androidaps.plugins.Overview.events.EventOverviewBolusProgress;
import info.nightscout.androidaps.plugins.VirtualPump.events.EventVirtualPumpUpdateGui; import info.nightscout.androidaps.plugins.VirtualPump.events.EventVirtualPumpUpdateGui;
import info.nightscout.client.data.NSProfile; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.utils.DateUtil; import info.nightscout.utils.DateUtil;
/** /**
@ -158,12 +158,12 @@ public class VirtualPumpPlugin implements PluginBase, PumpInterface {
} }
@Override @Override
public Date lastStatusTime() { public Date lastDataTime() {
return new Date(); return new Date();
} }
@Override @Override
public void updateStatus(String reason) { public void refreshDataFromPump(String reason) {
// do nothing // do nothing
} }

View file

@ -1,21 +1,11 @@
package info.nightscout.androidaps.plugins.Wear; package info.nightscout.androidaps.plugins.Wear;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Handler; import android.os.Handler;
import android.os.HandlerThread; import android.os.HandlerThread;
import android.preference.PreferenceManager;
import android.support.annotation.BoolRes;
import android.support.annotation.NonNull; import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.view.View;
import com.j256.ormlite.dao.Dao; import com.j256.ormlite.dao.Dao;
import org.json.JSONException;
import org.json.JSONObject;
import java.sql.SQLException; import java.sql.SQLException;
import java.text.DecimalFormat; import java.text.DecimalFormat;
import java.util.Date; import java.util.Date;
@ -32,15 +22,14 @@ import info.nightscout.androidaps.db.TempTarget;
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.plugins.Actions.dialogs.FillDialog; import info.nightscout.androidaps.plugins.Actions.dialogs.FillDialog;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.Loop.LoopPlugin; import info.nightscout.androidaps.plugins.Loop.LoopPlugin;
import info.nightscout.androidaps.plugins.Overview.QuickWizard; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.androidaps.plugins.TempTargetRange.TempTargetRangePlugin; import info.nightscout.androidaps.plugins.TempTargetRange.TempTargetRangePlugin;
import info.nightscout.androidaps.plugins.TempTargetRange.events.EventTempTargetRangeChange; import info.nightscout.androidaps.plugins.TempTargetRange.events.EventTempTargetRangeChange;
import info.nightscout.client.data.NSProfile;
import info.nightscout.utils.BolusWizard; import info.nightscout.utils.BolusWizard;
import info.nightscout.utils.DateUtil; import info.nightscout.utils.DateUtil;
import info.nightscout.utils.DecimalFormatter; import info.nightscout.utils.DecimalFormatter;
import info.nightscout.utils.SP;
import info.nightscout.utils.SafeParse; import info.nightscout.utils.SafeParse;
import info.nightscout.utils.ToastUtils; import info.nightscout.utils.ToastUtils;
@ -56,9 +45,6 @@ public class ActionStringHandler {
private static String lastConfirmActionString = null; private static String lastConfirmActionString = null;
private static BolusWizard lastBolusWizard = null; private static BolusWizard lastBolusWizard = null;
private static SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext());
private static HandlerThread handlerThread = new HandlerThread(FillDialog.class.getSimpleName()); private static HandlerThread handlerThread = new HandlerThread(FillDialog.class.getSimpleName());
static { static {
handlerThread.start(); handlerThread.start();
@ -83,11 +69,11 @@ public class ActionStringHandler {
///////////////////////////////////// PRIME/FILL ///////////////////////////////////// PRIME/FILL
double amount = 0d; double amount = 0d;
if ("1".equals(act[1])) { if ("1".equals(act[1])) {
amount = SafeParse.stringToDouble(DecimalFormatter.to2Decimal(SafeParse.stringToDouble(sp.getString("fill_button1", "0.3")))); amount = SP.getDouble("fill_button1", 0.3);
} else if ("2".equals(act[1])) { } else if ("2".equals(act[1])) {
amount = SafeParse.stringToDouble(DecimalFormatter.to2Decimal(SafeParse.stringToDouble(sp.getString("fill_button2", "0")))); amount = SP.getDouble("fill_button2", 0d);
} else if ("3".equals(act[1])) { } else if ("3".equals(act[1])) {
amount = SafeParse.stringToDouble(DecimalFormatter.to2Decimal(SafeParse.stringToDouble(sp.getString("fill_button3", "0")))); amount = SP.getDouble("fill_button3", 0d);
} else { } else {
return; return;
} }
@ -305,17 +291,17 @@ public class ActionStringHandler {
} }
//Default Range/Target //Default Range/Target
String maxBgDefault = Constants.MAX_BG_DEFAULT_MGDL; Double maxBgDefault = Constants.MAX_BG_DEFAULT_MGDL;
String minBgDefault = Constants.MIN_BG_DEFAULT_MGDL; Double minBgDefault = Constants.MIN_BG_DEFAULT_MGDL;
String targetBgDefault = Constants.TARGET_BG_DEFAULT_MGDL; Double targetBgDefault = Constants.TARGET_BG_DEFAULT_MGDL;
if (!profile.getUnits().equals(Constants.MGDL)) { if (!profile.getUnits().equals(Constants.MGDL)) {
maxBgDefault = Constants.MAX_BG_DEFAULT_MMOL; maxBgDefault = Constants.MAX_BG_DEFAULT_MMOL;
minBgDefault = Constants.MIN_BG_DEFAULT_MMOL; minBgDefault = Constants.MIN_BG_DEFAULT_MMOL;
targetBgDefault = Constants.TARGET_BG_DEFAULT_MMOL; targetBgDefault = Constants.TARGET_BG_DEFAULT_MMOL;
} }
ret += "DEFAULT RANGE: "; ret += "DEFAULT RANGE: ";
ret += sp.getString("openapsma_min_bg", minBgDefault) + " - " + sp.getString("openapsma_max_bg", maxBgDefault); ret += SP.getDouble("openapsma_min_bg", minBgDefault) + " - " + SP.getDouble("openapsma_max_bg", maxBgDefault);
ret += " target: " + sp.getString("openapsma_target_bg", targetBgDefault); ret += " target: " + SP.getDouble("openapsma_target_bg", targetBgDefault);
return ret; return ret;
} }

View file

@ -35,7 +35,7 @@ import info.nightscout.androidaps.plugins.Loop.LoopPlugin;
import info.nightscout.androidaps.plugins.Overview.OverviewPlugin; import info.nightscout.androidaps.plugins.Overview.OverviewPlugin;
import info.nightscout.androidaps.plugins.Wear.ActionStringHandler; import info.nightscout.androidaps.plugins.Wear.ActionStringHandler;
import info.nightscout.androidaps.plugins.Wear.WearPlugin; import info.nightscout.androidaps.plugins.Wear.WearPlugin;
import info.nightscout.client.data.NSProfile; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSProfile;
import info.nightscout.utils.DecimalFormatter; import info.nightscout.utils.DecimalFormatter;
import info.nightscout.utils.SafeParse; import info.nightscout.utils.SafeParse;
import info.nightscout.utils.ToastUtils; import info.nightscout.utils.ToastUtils;

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