Merge branch 'dev' into omnipod_eros_bart

This commit is contained in:
Bart Sopers 2019-10-02 19:18:44 +02:00
commit 953210be78
170 changed files with 3275 additions and 1614 deletions

View file

@ -109,7 +109,7 @@ android {
targetSdkVersion 28
multiDexEnabled true
versionCode 1500
version "2.4-dev-f"
version "2.4-dev-g"
buildConfigField "String", "VERSION", '"' + version + '"'
buildConfigField "String", "BUILDVERSION", '"' + generateGitBuild() + '-' + generateDate() + '"'
buildConfigField "String", "REMOTE", '"' + generateGitRemote() + '"'
@ -291,9 +291,11 @@ dependencies {
}
testImplementation "org.skyscreamer:jsonassert:1.5.0"
testImplementation "org.hamcrest:hamcrest-all:1.3"
/*
testImplementation("uk.org.lidalia:slf4j-test:1.2.0") {
exclude group: "com.google.guava", module: "guava"
}
*/
androidTestImplementation "org.mockito:mockito-core:2.8.47"
androidTestImplementation "com.google.dexmaker:dexmaker:${dexmakerVersion}"

View file

@ -36,6 +36,8 @@ public class Constants {
public static final int CPP_MIN_TIMESHIFT = -6;
public static final int CPP_MAX_TIMESHIFT = 23;
public static final double MAX_PROFILE_SWITCH_DURATION = 7 * 24 * 60; // [min] ~ 7 days
//DanaR
public static final double dailyLimitWarning = 0.95d;

View file

@ -199,7 +199,7 @@ public class MainActivity extends NoSplashAppCompatActivity {
} else {
try { // activity may be destroyed
setupTabs();
setupViews(true);
setupViews(false);
} catch (IllegalStateException e) {
log.error("Unhandled exception", e);
}

View file

@ -54,7 +54,6 @@ import info.nightscout.androidaps.plugins.general.overview.OverviewPlugin;
import info.nightscout.androidaps.plugins.general.persistentNotification.PersistentNotificationPlugin;
import info.nightscout.androidaps.plugins.general.signatureVerifier.SignatureVerifier;
import info.nightscout.androidaps.plugins.general.smsCommunicator.SmsCommunicatorPlugin;
import info.nightscout.androidaps.plugins.general.tidepool.TidepoolPlugin;
import info.nightscout.androidaps.plugins.general.versionChecker.VersionCheckerPlugin;
import info.nightscout.androidaps.plugins.general.wear.WearPlugin;
import info.nightscout.androidaps.plugins.general.xdripStatusline.StatuslinePlugin;
@ -170,7 +169,7 @@ public class MainApp extends Application {
if (pluginsList == null) {
pluginsList = new ArrayList<>();
// Register all tabs in app here
pluginsList.add(OverviewPlugin.getPlugin());
pluginsList.add(OverviewPlugin.INSTANCE);
pluginsList.add(IobCobCalculatorPlugin.getPlugin());
if (Config.ACTION) pluginsList.add(ActionsPlugin.INSTANCE);
pluginsList.add(InsulinOrefRapidActingPlugin.getPlugin());

View file

@ -230,8 +230,8 @@ public class HistoryBrowseActivity extends NoSplashActivity {
}
final String units = profile.getUnits();
final double lowLine = OverviewPlugin.getPlugin().determineLowLine(units);
final double highLine = OverviewPlugin.getPlugin().determineHighLine(units);
final double lowLine = OverviewPlugin.INSTANCE.determineLowLine(units);
final double highLine = OverviewPlugin.INSTANCE.determineHighLine(units);
buttonDate.setText(DateUtil.dateAndTimeString(start));
buttonZoom.setText(String.valueOf(rangeToDisplay));

View file

@ -209,6 +209,7 @@ public class PreferencesActivity extends PreferenceActivity implements SharedPre
scrnAdvancedSettings.removePreference(getPreference(getString(R.string.key_statuslights_bat_warning)));
scrnAdvancedSettings.removePreference(getPreference(getString(R.string.key_statuslights_bat_critical)));
scrnAdvancedSettings.removePreference(getPreference(getString(R.string.key_show_statuslights)));
scrnAdvancedSettings.removePreference(getPreference(getString(R.string.key_show_statuslights_extended)));
}
}

View file

@ -17,6 +17,7 @@ import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.interfaces.PumpDescription;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification;
@ -231,7 +232,7 @@ public class Profile {
if (notify && secondsFromMidnight % 3600 != 0) {
if (Config.APS) {
Notification notification = new Notification(Notification.BASAL_PROFILE_NOT_ALIGNED_TO_HOURS, String.format(MainApp.gs(R.string.basalprofilenotaligned), from), Notification.NORMAL);
MainApp.bus().post(new EventNewNotification(notification));
RxBus.INSTANCE.send(new EventNewNotification(notification));
}
}
}
@ -263,11 +264,11 @@ public class Profile {
}
protected void sendBelowMinimumNotification(String from) {
MainApp.bus().post(new EventNewNotification(new Notification(Notification.MINIMAL_BASAL_VALUE_REPLACED, String.format(MainApp.gs(R.string.minimalbasalvaluereplaced), from), Notification.NORMAL)));
RxBus.INSTANCE.send(new EventNewNotification(new Notification(Notification.MINIMAL_BASAL_VALUE_REPLACED, String.format(MainApp.gs(R.string.minimalbasalvaluereplaced), from), Notification.NORMAL)));
}
protected void sendAboveMaximumNotification(String from) {
MainApp.bus().post(new EventNewNotification(new Notification(Notification.MAXIMUM_BASAL_VALUE_REPLACED, String.format(MainApp.gs(R.string.maximumbasalvaluereplaced), from), Notification.NORMAL)));
RxBus.INSTANCE.send(new EventNewNotification(new Notification(Notification.MAXIMUM_BASAL_VALUE_REPLACED, String.format(MainApp.gs(R.string.maximumbasalvaluereplaced), from), Notification.NORMAL)));
}
private void validate(LongSparseArray array) {

View file

@ -1,86 +0,0 @@
package info.nightscout.androidaps.data;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.utils.SP;
/**
* Created by mike on 12.10.2016.
*/
public class QuickWizard {
private static Logger log = LoggerFactory.getLogger(QuickWizard.class);
private JSONArray storage = new JSONArray();
public void setData(JSONArray newData) {
storage = newData;
}
public void save() {
SP.putString("QuickWizard", storage.toString());
}
public int size() {
return storage.length();
}
public QuickWizardEntry get(int position) {
try {
return new QuickWizardEntry((JSONObject) storage.get(position), position);
} catch (JSONException e) {
log.error("Unhandled exception", e);
}
return null;
}
public Boolean isActive() {
for (int i = 0; i < storage.length(); i++) {
try {
if (new QuickWizardEntry((JSONObject) storage.get(i), i).isActive()) return true;
} catch (JSONException e) {
log.error("Unhandled exception", e);
}
}
return false;
}
public QuickWizardEntry getActive() {
for (int i = 0; i < storage.length(); i++) {
QuickWizardEntry entry;
try {
entry = new QuickWizardEntry((JSONObject) storage.get(i), i);
} catch (JSONException e) {
continue;
}
if (entry.isActive()) return entry;
}
return null;
}
public QuickWizardEntry newEmptyItem() {
return new QuickWizardEntry();
}
public void addOrUpdate(QuickWizardEntry newItem) {
if (newItem.position == -1)
storage.put(newItem.storage);
else {
try {
storage.put(newItem.position, newItem.storage);
} catch (JSONException e) {
log.error("Unhandled exception", e);
}
}
save();
}
public void remove(int position) {
storage.remove(position);
save();
}
}

View file

@ -0,0 +1,52 @@
package info.nightscout.androidaps.data
import info.nightscout.androidaps.utils.SP
import org.json.JSONArray
import org.json.JSONObject
object QuickWizard {
private var storage = JSONArray()
init {
setData(JSONArray(SP.getString("QuickWizard", "[]")))
}
fun getActive(): QuickWizardEntry? {
for (i in 0 until storage.length()) {
val entry = QuickWizardEntry(storage.get(i) as JSONObject, i)
if (entry.isActive) return entry
}
return null
}
fun setData(newData: JSONArray) {
storage = newData
}
fun save() {
SP.putString("QuickWizard", storage.toString())
}
fun size(): Int = storage.length()
operator fun get(position: Int): QuickWizardEntry =
QuickWizardEntry(storage.get(position) as JSONObject, position)
fun newEmptyItem(): QuickWizardEntry {
return QuickWizardEntry()
}
fun addOrUpdate(newItem: QuickWizardEntry) {
if (newItem.position == -1)
storage.put(newItem.storage)
else
storage.put(newItem.position, newItem.storage)
save()
}
fun remove(position: Int) {
storage.remove(position)
save()
}
}

View file

@ -216,8 +216,8 @@ public class BgReading implements DataPointWithLabelInterface {
@Override
public int getColor() {
String units = ProfileFunctions.getInstance().getProfileUnits();
Double lowLine = OverviewPlugin.getPlugin().determineLowLine(units);
Double highLine = OverviewPlugin.getPlugin().determineHighLine(units);
Double lowLine = OverviewPlugin.INSTANCE.determineLowLine(units);
Double highLine = OverviewPlugin.INSTANCE.determineHighLine(units);
int color = MainApp.gc(R.color.inrange);
if (isPrediction())
return getPredectionColor();

View file

@ -1,6 +1,8 @@
package info.nightscout.androidaps.db;
import android.graphics.Color;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.j256.ormlite.field.DatabaseField;
@ -18,11 +20,13 @@ import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.interfaces.Interval;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.general.overview.graphExtensions.DataPointWithLabelInterface;
import info.nightscout.androidaps.plugins.general.overview.graphExtensions.PointsWithLabelGraphSeries;
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification;
import info.nightscout.androidaps.plugins.profile.local.LocalProfilePlugin;
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.DecimalFormatter;
import info.nightscout.androidaps.utils.T;
@ -78,12 +82,12 @@ public class ProfileSwitch implements Interval, DataPointWithLabelInterface {
return this;
}
public ProfileSwitch source(int source) {
public ProfileSwitch source(int source) {
this.source = source;
return this;
}
public ProfileSwitch duration(int duration) {
public ProfileSwitch duration(int duration) {
this.durationInMinutes = duration;
return this;
}
@ -107,7 +111,7 @@ public class ProfileSwitch implements Interval, DataPointWithLabelInterface {
*/
public String getCustomizedName() {
String name = profileName;
if(LocalProfilePlugin.LOCAL_PROFILE.equals(name)){
if (LocalProfilePlugin.LOCAL_PROFILE.equals(name)) {
name = DecimalFormatter.to2Decimal(getProfileObject().percentageBasalSum()) + "U ";
}
if (isCPP) {
@ -156,7 +160,7 @@ public class ProfileSwitch implements Interval, DataPointWithLabelInterface {
// -------- Interval interface ---------
Long cuttedEnd = null;
private Long cuttedEnd = null;
public long durationInMsec() {
return durationInMinutes * 60 * 1000L;
@ -212,16 +216,17 @@ public class ProfileSwitch implements Interval, DataPointWithLabelInterface {
@Override
public boolean isValid() {
boolean isValid = getProfileObject() != null && getProfileObject().isValid(DateUtil.dateAndTimeString(date));
if (!isValid)
ProfileSwitch active = TreatmentsPlugin.getPlugin().getProfileSwitchFromHistory(DateUtil.now());
long activeProfileSwitchDate = active != null ? active.date : -1L;
if (!isValid && date == activeProfileSwitchDate)
createNotificationInvalidProfile(DateUtil.dateAndTimeString(date));
return isValid;
}
public void createNotificationInvalidProfile(String detail) {
private void createNotificationInvalidProfile(String detail) {
Notification notification = new Notification(Notification.ZERO_VALUE_IN_PROFILE, String.format(MainApp.gs(R.string.zerovalueinprofile), detail), Notification.LOW, 5);
MainApp.bus().post(new EventNewNotification(notification));
RxBus.INSTANCE.send(new EventNewNotification(notification));
}
public static boolean isEvent5minBack(List<ProfileSwitch> list, long time, boolean zeroDurationOnly) {
@ -290,6 +295,7 @@ public class ProfileSwitch implements Interval, DataPointWithLabelInterface {
return Color.CYAN;
}
@NonNull
public String toString() {
return "ProfileSwitch{" +
"date=" + date +

View file

@ -68,6 +68,7 @@ class ConfigBuilderFragment : Fragment() {
@Synchronized
private fun updateGUI() {
configbuilder_categories.removeAllViews()
createViewsForPlugins(R.string.configbuilder_profile, R.string.configbuilder_profile_description, PluginType.PROFILE, MainApp.getSpecificPluginsVisibleInListByInterface(ProfileInterface::class.java, PluginType.PROFILE))
createViewsForPlugins(R.string.configbuilder_insulin, R.string.configbuilder_insulin_description, PluginType.INSULIN, MainApp.getSpecificPluginsVisibleInListByInterface(InsulinInterface::class.java, PluginType.INSULIN))
createViewsForPlugins(R.string.configbuilder_bgsource, R.string.configbuilder_bgsource_description, PluginType.BGSOURCE, MainApp.getSpecificPluginsVisibleInListByInterface(BgSourceInterface::class.java, PluginType.BGSOURCE))

View file

@ -15,6 +15,7 @@ import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin;
import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification;
@ -89,6 +90,6 @@ public class DstHelperPlugin extends PluginBase implements ConstraintsInterface
private void warnUser(int id, String warningText) {
Notification notification = new Notification(id, warningText, Notification.LOW);
MainApp.bus().post(new EventNewNotification(notification));
RxBus.INSTANCE.send(new EventNewNotification(notification));
}
}

View file

@ -18,19 +18,20 @@ import androidx.recyclerview.widget.LinearSmoothScroller
import androidx.recyclerview.widget.RecyclerView
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R
import info.nightscout.androidaps.logging.L
import info.nightscout.androidaps.plugins.bus.RxBus
import info.nightscout.androidaps.plugins.constraints.objectives.activities.ObjectivesExamDialog
import info.nightscout.androidaps.plugins.constraints.objectives.events.EventObjectivesUpdateGui
import info.nightscout.androidaps.plugins.constraints.objectives.objectives.Objective.ExamTask
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.HtmlHelper
import info.nightscout.androidaps.utils.SP
import info.nightscout.androidaps.receivers.NetworkChangeReceiver
import info.nightscout.androidaps.utils.*
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import kotlinx.android.synthetic.main.objectives_fragment.*
import org.slf4j.LoggerFactory
class ObjectivesFragment : Fragment() {
private val log = LoggerFactory.getLogger(L.CONSTRAINTS)
private val objectivesAdapter = ObjectivesAdapter()
private val handler = Handler(Looper.getMainLooper())
@ -168,10 +169,17 @@ class ObjectivesFragment : Fragment() {
holder.progress.removeAllViews()
for (task in objective.tasks) {
if (task.shouldBeIgnored()) continue
// name
val name = TextView(holder.progress.context)
name.text = MainApp.gs(task.task) + ":"
name.setTextColor(-0x1)
holder.progress.addView(name, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)
// hint
task.hints.forEach { h ->
if (!task.isCompleted)
holder.progress.addView(h.generate(context))
}
// state
val state = TextView(holder.progress.context)
state.setTextColor(-0x1)
val basicHTML = "<font color=\"%1\$s\"><b>%2\$s</b></font>"
@ -183,13 +191,14 @@ class ObjectivesFragment : Fragment() {
state.setOnClickListener {
val dialog = ObjectivesExamDialog()
val bundle = Bundle()
val position = objective.tasks.indexOf(task)
bundle.putInt("currentTask", position)
val taskPosition = objective.tasks.indexOf(task)
bundle.putInt("currentTask", taskPosition)
dialog.arguments = bundle
ObjectivesExamDialog.objective = objective
fragmentManager?.let { dialog.show(it, "ObjectivesFragment") }
}
}
// horizontal line
val separator = View(holder.progress.context)
separator.setBackgroundColor(Color.DKGRAY)
holder.progress.addView(separator, LinearLayout.LayoutParams.MATCH_PARENT, 2)
@ -198,16 +207,50 @@ class ObjectivesFragment : Fragment() {
holder.accomplished.text = MainApp.gs(R.string.accomplished, DateUtil.dateAndTimeString(objective.accomplishedOn))
holder.accomplished.setTextColor(-0x3e3e3f)
holder.verify.setOnClickListener {
objective.accomplishedOn = DateUtil.now()
notifyDataSetChanged()
scrollToCurrentObjective()
startUpdateTimer()
holder.verify.visibility = View.INVISIBLE
SntpClient.ntpTime(object : SntpClient.Callback() {
override fun run() {
activity?.runOnUiThread {
holder.verify.visibility = View.VISIBLE
log.debug("NTP time: $time System time: ${DateUtil.now()}")
if (!networkConnected) {
ToastUtils.showToastInUiThread(context, R.string.notconnected)
} else if (success) {
if (objective.isCompleted(time)) {
objective.accomplishedOn = time
notifyDataSetChanged()
scrollToCurrentObjective()
startUpdateTimer()
} else {
ToastUtils.showToastInUiThread(context, R.string.requirementnotmet)
}
} else {
ToastUtils.showToastInUiThread(context, R.string.failedretrievetime)
}
}
}
}, NetworkChangeReceiver.isConnected())
}
holder.start.setOnClickListener {
objective.startedOn = DateUtil.now()
notifyDataSetChanged()
scrollToCurrentObjective()
startUpdateTimer()
holder.start.visibility = View.INVISIBLE
SntpClient.ntpTime(object : SntpClient.Callback() {
override fun run() {
activity?.runOnUiThread {
holder.start.visibility = View.VISIBLE
log.debug("NTP time: $time System time: ${DateUtil.now()}")
if (!networkConnected) {
ToastUtils.showToastInUiThread(context, R.string.notconnected)
} else if (success) {
objective.startedOn = time
notifyDataSetChanged()
scrollToCurrentObjective()
startUpdateTimer()
} else {
ToastUtils.showToastInUiThread(context, R.string.failedretrievetime)
}
}
}
}, NetworkChangeReceiver.isConnected())
}
holder.revert.setOnClickListener {
objective.accomplishedOn = 0

View file

@ -64,7 +64,7 @@ object ObjectivesPlugin : PluginBase(PluginDescription()
private fun doConvertSP(number: Int, name: String) {
if (!SP.contains("Objectives_" + name + "_started")) {
SP.putLong("Objectives_" + name + "_started", SP.getLong("Objectives" + number + "accomplished", 0L))
SP.putLong("Objectives_" + name + "_started", SP.getLong("Objectives" + number + "started", 0L))
SP.putLong("Objectives_" + name + "_accomplished", SP.getLong("Objectives" + number + "accomplished", 0L))
}
// TODO: we can remove Objectives1accomplished sometimes later

View file

@ -70,8 +70,7 @@ class ObjectivesExamDialog : DialogFragment() {
// Hints
objectives_exam_hints.removeAllViews()
for (h in task.hints) {
val hint: Hint = h as Hint;
objectives_exam_hints.addView(hint.generate(context))
objectives_exam_hints.addView(h.generate(context))
}
// Disabled to
objectives_exam_disabledto.text = MainApp.gs(R.string.answerdisabledto, DateUtil.timeString(task.disabledTo))

View file

@ -4,6 +4,7 @@ import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.text.util.Linkify;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;
@ -36,6 +37,10 @@ public abstract class Objective {
this.gate = gate;
startedOn = SP.getLong("Objectives_" + spName + "_started", 0L);
accomplishedOn = SP.getLong("Objectives_" + spName + "_accomplished", 0L);
if ((accomplishedOn - DateUtil.now()) > T.days(1).msecs()) { // more than 1 day in the future
setStartedOn(0);
setAccomplishedOn(0);
}
setupTasks(tasks);
for (Task task : tasks) task.objective = this;
}
@ -48,12 +53,20 @@ public abstract class Objective {
return true;
}
public boolean isCompleted(long trueTime) {
for (Task task : tasks) {
if (!task.shouldBeIgnored() && !task.isCompleted(trueTime))
return false;
}
return true;
}
public boolean isRevertable() {
return false;
}
public boolean isAccomplished() {
return accomplishedOn != 0;
return accomplishedOn != 0 && accomplishedOn < DateUtil.now();
}
public boolean isStarted() {
@ -100,6 +113,7 @@ public abstract class Objective {
@StringRes
private int task;
private Objective objective;
ArrayList<Hint> hints = new ArrayList<>();
public Task(@StringRes int task) {
this.task = task;
@ -114,11 +128,21 @@ public abstract class Objective {
}
public abstract boolean isCompleted();
public boolean isCompleted(long trueTime) { return isCompleted(); };
public String getProgress() {
return MainApp.gs(isCompleted() ? R.string.completed_well_done : R.string.not_completed_yet);
}
Task hint(Hint hint) {
hints.add(hint);
return this;
}
public ArrayList<Hint> getHints() {
return hints;
}
public boolean shouldBeIgnored() {
return false;
}
@ -138,6 +162,11 @@ public abstract class Objective {
return getObjective().isStarted() && System.currentTimeMillis() - getObjective().getStartedOn() >= minimumDuration;
}
@Override
public boolean isCompleted(long trueTime) {
return getObjective().isStarted() && trueTime - getObjective().getStartedOn() >= minimumDuration;
}
@Override
public String getProgress() {
return getDurationText(System.currentTimeMillis() - getObjective().getStartedOn())
@ -157,8 +186,7 @@ public abstract class Objective {
public class ExamTask extends Task {
@StringRes
int question;
List hints = new ArrayList<>();
List options = new ArrayList<>();
ArrayList<Option> options = new ArrayList<>();
private String spIdentifier;
private boolean answered;
private long disabledTo;
@ -198,11 +226,6 @@ public abstract class Objective {
return this;
}
ExamTask hint(Hint hint) {
hints.add(hint);
return this;
}
public @StringRes int getQuestion() {
return question;
}
@ -211,10 +234,6 @@ public abstract class Objective {
return options;
}
public List getHints() {
return hints;
}
@Override
public boolean isCompleted() {
return answered;

View file

@ -4,7 +4,6 @@ import java.util.List;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.plugins.constraints.objectives.ObjectivesPlugin;
import info.nightscout.androidaps.plugins.general.actions.ActionsPlugin;
import info.nightscout.androidaps.utils.SP;
@ -28,36 +27,36 @@ public class Objective1 extends Objective {
public boolean isCompleted() {
return SP.getBoolean(R.string.key_objectiveusedisconnect, false);
}
});
}.hint(new Hint(R.string.disconnectpump_hint)));
tasks.add(new Task(R.string.objectives_usereconnectpump) {
@Override
public boolean isCompleted() {
return SP.getBoolean(R.string.key_objectiveusereconnect, false);
}
});
}.hint(new Hint(R.string.disconnectpump_hint)));
tasks.add(new Task(R.string.objectives_usetemptarget) {
@Override
public boolean isCompleted() {
return SP.getBoolean(R.string.key_objectiveusetemptarget, false);
}
});
}.hint(new Hint(R.string.usetemptarget_hint)));
tasks.add(new Task(R.string.objectives_useactions) {
@Override
public boolean isCompleted() {
return SP.getBoolean(R.string.key_objectiveuseactions, false) && ActionsPlugin.INSTANCE.isEnabled(PluginType.GENERAL) && ActionsPlugin.INSTANCE.isFragmentVisible();
}
});
}.hint(new Hint(R.string.useaction_hint)));
tasks.add(new Task(R.string.objectives_useloop) {
@Override
public boolean isCompleted() {
return SP.getBoolean(R.string.key_objectiveuseloop, false);
}
});
}.hint(new Hint(R.string.useaction_hint)));
tasks.add(new Task(R.string.objectives_usescale) {
@Override
public boolean isCompleted() {
return SP.getBoolean(R.string.key_objectiveusescale, false);
}
});
}.hint(new Hint(R.string.usescale_hint)));
}
}

View file

@ -26,7 +26,6 @@ public class Objective2 extends Objective {
);
tasks.add(new ExamTask(R.string.hypott_label, R.string.hypott_whenhypott,"hypott")
.option(new Option(R.string.hypott_goinglow, false))
.option(new Option(R.string.hypott_havinglow, false))
.option(new Option(R.string.hypott_preventoversmb, true))
.hint(new Hint(R.string.hypott_hint1))
);
@ -66,7 +65,6 @@ public class Objective2 extends Objective {
.option(new Option(R.string.exercise_switchprofileabove100, false))
.option(new Option(R.string.exercise_stoploop, false))
.option(new Option(R.string.exercise_doitbeforestart, true))
.option(new Option(R.string.exercise_doitafterstart, false))
.hint(new Hint(R.string.exercise_hint1))
);
tasks.add(new ExamTask(R.string.suspendloop_label, R.string.suspendloop_doigetinsulin,"suspendloop")
@ -79,6 +77,12 @@ public class Objective2 extends Objective {
.option(new Option(R.string.basaltest_havingregularhyper, true))
.hint(new Hint(R.string.basaltest_hint1))
);
tasks.add(new ExamTask(R.string.basalhelp_label, R.string.basalhelp_where,"basalhelp")
.option(new Option(R.string.basalhelp_diabetesteam, true))
.option(new Option(R.string.basalhelp_google, false))
.option(new Option(R.string.basalhelp_facebook, false))
.hint(new Hint(R.string.basalhelp_hint1))
);
tasks.add(new ExamTask(R.string.prerequisites_label, R.string.prerequisites_what, "prerequisites")
.option(new Option(R.string.prerequisites_determinedcorrectprofile, true))
.option(new Option(R.string.prerequisites_computer, true))
@ -151,6 +155,7 @@ public class Objective2 extends Objective {
.option(new Option(R.string.nsclient_xdripfollower, true))
.option(new Option(R.string.nsclient_looponiphone, false))
.option(new Option(R.string.nsclient_spikeiphone, true))
.hint(new Hint(R.string.nsclient_hint1))
);
tasks.add(new ExamTask(R.string.isf_label, R.string.whatistrue,"isf")
.option(new Option(R.string.isf_increasingvalue, true))
@ -195,9 +200,4 @@ public class Objective2 extends Objective {
Collections.shuffle(((ExamTask)task).options);
}
@Override
public boolean isRevertable() {
return true;
}
}

View file

@ -16,6 +16,7 @@ import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.plugins.aps.openAPSAMA.OpenAPSAMAPlugin;
import info.nightscout.androidaps.plugins.aps.openAPSMA.OpenAPSMAPlugin;
import info.nightscout.androidaps.plugins.aps.openAPSSMB.OpenAPSSMBPlugin;
import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification;
@ -68,7 +69,7 @@ public class SafetyPlugin extends PluginBase implements ConstraintsInterface {
if (!MainApp.isEngineeringModeOrRelease()) {
if (value.value()) {
Notification n = new Notification(Notification.TOAST_ALARM, MainApp.gs(R.string.closed_loop_disabled_on_dev_branch), Notification.NORMAL);
MainApp.bus().post(new EventNewNotification(n));
RxBus.INSTANCE.send(new EventNewNotification(n));
}
value.set(false, MainApp.gs(R.string.closed_loop_disabled_on_dev_branch), this);
}
@ -125,6 +126,10 @@ public class SafetyPlugin extends PluginBase implements ConstraintsInterface {
if (Config.APS) {
double maxBasal = SP.getDouble(R.string.key_openapsma_max_basal, 1d);
if (maxBasal < profile.getMaxDailyBasal()) {
maxBasal = profile.getMaxDailyBasal();
absoluteRate.addReason(MainApp.gs(R.string.increasingmaxbasal), this);
}
absoluteRate.setIfSmaller(maxBasal, String.format(MainApp.gs(R.string.limitingbasalratio), maxBasal, MainApp.gs(R.string.maxvalueinpreferences)), this);
// Check percentRate but absolute rate too, because we know real current basal in pump

View file

@ -17,6 +17,7 @@ import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginDescription;
import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification;
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification;
@ -56,9 +57,9 @@ public class StorageConstraintPlugin extends PluginBase implements ConstraintsIn
if (diskfree < Constants.MINIMUM_FREE_SPACE) {
value.set(false, MainApp.gs(R.string.diskfull, Constants.MINIMUM_FREE_SPACE), this);
Notification notification = new Notification(Notification.DISKFULL, MainApp.gs(R.string.diskfull, Constants.MINIMUM_FREE_SPACE), Notification.NORMAL);
MainApp.bus().post(new EventNewNotification(notification));
RxBus.INSTANCE.send(new EventNewNotification(notification));
} else {
MainApp.bus().post(new EventDismissNotification(Notification.DISKFULL));
RxBus.INSTANCE.send(new EventDismissNotification(Notification.DISKFULL));
}
return value;

View file

@ -77,7 +77,7 @@ class AutomationFragment : Fragment() {
if (eventListAdapter == null) return
eventListAdapter?.notifyDataSetChanged()
val sb = StringBuilder()
for (l in AutomationPlugin.executionLog) {
for (l in AutomationPlugin.executionLog.reversed()) {
sb.append(l)
sb.append("\n")
}

View file

@ -201,7 +201,8 @@ object AutomationPlugin : PluginBase(PluginDescription()
ActionStartTempTarget(),
ActionStopTempTarget(),
ActionNotification(),
ActionProfileSwitchPercent()
ActionProfileSwitchPercent(),
ActionProfileSwitch()
)
}
@ -209,6 +210,7 @@ object AutomationPlugin : PluginBase(PluginDescription()
return listOf(
TriggerTime(),
TriggerRecurringTime(),
TriggerTimeRange(),
TriggerBg(),
TriggerDelta(),
TriggerIob(),

View file

@ -0,0 +1,118 @@
package info.nightscout.androidaps.plugins.general.automation.actions;
import android.widget.LinearLayout;
import com.google.common.base.Optional;
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.R;
import info.nightscout.androidaps.data.ProfileStore;
import info.nightscout.androidaps.data.PumpEnactResult;
import info.nightscout.androidaps.interfaces.ProfileInterface;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.general.automation.elements.InputProfileName;
import info.nightscout.androidaps.plugins.general.automation.elements.LabelWithElement;
import info.nightscout.androidaps.plugins.general.automation.elements.LayoutBuilder;
import info.nightscout.androidaps.queue.Callback;
import info.nightscout.androidaps.utils.JsonHelper;
public class ActionProfileSwitch extends Action {
private static Logger log = LoggerFactory.getLogger(L.AUTOMATION);
public InputProfileName inputProfileName = new InputProfileName(ProfileFunctions.getInstance().getProfileName());
String profileName = "";
public ActionProfileSwitch() {
// Prevent action if active profile is already active
// but we don't have a trigger IS_NOT_EQUAL
// so check is in the doRun()
}
@Override
public int friendlyName() {
return R.string.profilename;
}
@Override
public String shortDescription() {
String returned = MainApp.gs(R.string.changengetoprofilename, inputProfileName.getValue());
return returned;
}
@Override
public void doAction(Callback callback) {
String activeProfileName = ProfileFunctions.getInstance().getProfileName();
//Check for uninitialized profileName
if ( profileName.equals("")){ profileName = activeProfileName; }
if (profileName.equals(activeProfileName)) {
// Profile is already switched
return;
}
ProfileInterface activeProfile = ConfigBuilderPlugin.getPlugin().getActiveProfileInterface();
if (activeProfile == null) return;
ProfileStore profileStore = activeProfile.getProfile();
if (profileStore == null) return;
if(profileStore.getSpecificProfile(profileName) == null) {
if (L.isEnabled(L.AUTOMATION))
log.error("Selected profile does not exist! - "+ profileName);
return;
}
ProfileFunctions.doProfileSwitch(profileStore, profileName, 0, 100, 0);
if (callback != null)
callback.result(new PumpEnactResult().success(true).comment(R.string.ok)).run();
}
@Override
public void generateDialog(LinearLayout root) {
new LayoutBuilder()
.add(new LabelWithElement(MainApp.gs(R.string.profilename), "", inputProfileName))
.build(root);
}
@Override
public boolean hasDialog() {
return true;
}
@Override
public String toJSON() {
JSONObject o = new JSONObject();
try {
o.put("type", ActionProfileSwitch.class.getName());
JSONObject data = new JSONObject();
data.put("profileToSwitchTo", inputProfileName.getValue());
o.put("data", data);
} catch (JSONException e) {
e.printStackTrace();
}
return o.toString();
}
@Override
public Action fromJSON(String data) {
try {
JSONObject d = new JSONObject(data);
profileName = JsonHelper.safeGetString(d, "profileToSwitchTo");
inputProfileName.setValue(profileName);
} catch (JSONException e) {
e.printStackTrace();
}
return this;
}
@Override
public Optional<Integer> icon() {
return Optional.of(R.drawable.icon_actions_profileswitch);
}
}

View file

@ -56,6 +56,11 @@ class ChooseActionDialog : DialogFragment() {
cancel.setOnClickListener { dismiss() }
}
override fun onStart() {
super.onStart()
dialog?.window?.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
}
override fun onSaveInstanceState(bundle: Bundle) {
bundle.putInt("checkedIndex", determineCheckedIndex())
}

View file

@ -58,6 +58,11 @@ class ChooseTriggerDialog : DialogFragment() {
cancel.setOnClickListener { dismiss() }
}
override fun onStart() {
super.onStart()
dialog?.window?.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
}
fun setOnClickListener(clickListener: OnClickListener) {
this.clickListener = clickListener
}

View file

@ -14,7 +14,6 @@ import kotlinx.android.synthetic.main.okcancel.*
import org.json.JSONObject
class EditActionDialog : DialogFragment() {
private var action: Action? = null
private var actionPosition: Int = -1
@ -51,6 +50,11 @@ class EditActionDialog : DialogFragment() {
cancel.setOnClickListener { dismiss() }
}
override fun onStart() {
super.onStart()
dialog?.window?.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
}
override fun onSaveInstanceState(bundle: Bundle) {
super.onSaveInstanceState(bundle)
action?.let {

View file

@ -137,6 +137,11 @@ class EditEventDialog : DialogFragment() {
)
}
override fun onStart() {
super.onStart()
dialog?.window?.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
}
override fun onDestroyView() {
super.onDestroyView()
disposable.clear()

View file

@ -31,18 +31,23 @@ class EditTriggerDialog : DialogFragment() {
super.onViewCreated(view, savedInstanceState)
// display root trigger
trigger?.let { it.generateDialog(automation_layoutTrigger, fragmentManager) }
trigger?.generateDialog(automation_layoutTrigger, fragmentManager)
// OK button
ok.setOnClickListener {
dismiss()
RxBus.send(EventAutomationUpdateTrigger(trigger!!))
trigger?.let { trigger -> RxBus.send(EventAutomationUpdateTrigger(trigger)) }
}
// Cancel button
cancel.setOnClickListener { dismiss() }
}
override fun onStart() {
super.onStart()
dialog?.window?.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
}
override fun onSaveInstanceState(bundle: Bundle) {
super.onSaveInstanceState(bundle)
trigger?.let { bundle.putString("trigger", it.toJSON()) }

View file

@ -0,0 +1,99 @@
package info.nightscout.androidaps.plugins.general.automation.elements;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.Spinner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.data.ProfileStore;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
public class InputProfileName extends Element {
private static Logger log = LoggerFactory.getLogger(L.AUTOMATION);
ProfileStore profileStore;
String profileName;
public InputProfileName(String name) {
super();
this.profileName = name;
}
public InputProfileName(InputProfileName another) {
super();
profileName = another.getValue();
}
@Override
public void addToLayout(LinearLayout root) {
ArrayList<CharSequence> profileList = new ArrayList<>();
profileStore = ConfigBuilderPlugin.getPlugin().getActiveProfileInterface().getProfile();
if (profileStore == null) {
log.error("ProfileStore is empty");
} else {
profileList = profileStore.getProfileList();
}
ArrayAdapter<CharSequence> adapter = new ArrayAdapter<>(root.getContext(),
R.layout.spinner_centered, profileList);
Spinner spinner = new Spinner(root.getContext());
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
LinearLayout.LayoutParams spinnerParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT
);
spinnerParams.setMargins(0, MainApp.dpToPx(4), 0, MainApp.dpToPx(4));
spinner.setLayoutParams(spinnerParams);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
setValue(listNames().get(position).toString());
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
spinner.setSelection(0);
LinearLayout l = new LinearLayout(root.getContext());
l.setOrientation(LinearLayout.VERTICAL);
l.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
l.addView(spinner);
root.addView(l);
}
public InputProfileName setValue(String name) {
this.profileName = name;
return this;
}
public String getValue() {
return profileName;
}
public ArrayList<CharSequence> listNames(){
ArrayList<CharSequence> profileList = new ArrayList<>();
// profile
profileStore = ConfigBuilderPlugin.getPlugin().getActiveProfileInterface().getProfile();
if (profileStore == null) {
log.error("ProfileStore is empty");
} else {
profileList = profileStore.getProfileList();
}
return profileList;
}
}

View file

@ -63,16 +63,22 @@ public class TriggerBg extends Trigger {
public synchronized boolean shouldRun() {
GlucoseStatus glucoseStatus = GlucoseStatus.getGlucoseStatusData();
if (lastRun > DateUtil.now() - T.mins(5).msecs())
if (lastRun > DateUtil.now() - T.mins(5).msecs()) {
if (L.isEnabled(L.AUTOMATION))
log.debug("NOT ready for execution: " + friendlyDescription());
return false;
}
if (glucoseStatus == null && comparator.getValue().equals(Comparator.Compare.IS_NOT_AVAILABLE)) {
if (L.isEnabled(L.AUTOMATION))
log.debug("Ready for execution: " + friendlyDescription());
return true;
}
if (glucoseStatus == null)
if (glucoseStatus == null) {
if (L.isEnabled(L.AUTOMATION))
log.debug("NOT ready for execution: " + friendlyDescription());
return false;
}
boolean doRun = comparator.getValue().check(glucoseStatus.glucose, Profile.toMgdl(bg.getValue(), bg.getUnits()));
if (doRun) {
@ -80,6 +86,9 @@ public class TriggerBg extends Trigger {
log.debug("Ready for execution: " + friendlyDescription());
return true;
}
if (L.isEnabled(L.AUTOMATION))
log.debug("NOT ready for execution: " + friendlyDescription());
return false;
}

View file

@ -0,0 +1,236 @@
package info.nightscout.androidaps.plugins.general.automation.triggers;
import android.app.Activity;
import android.graphics.Typeface;
import android.text.format.DateFormat;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.fragment.app.FragmentManager;
import com.google.common.base.Optional;
import com.wdullaer.materialdatetimepicker.time.TimePickerDialog;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.JsonHelper;
import info.nightscout.androidaps.utils.T;
// Trigger for time range ( from 10:00AM till 13:00PM )
public class TriggerTimeRange extends Trigger {
private static Logger log = LoggerFactory.getLogger(L.AUTOMATION);
// in minutes since midnight 60 means 1AM
private int start;
private int end;
long timeZoneOffset = DateUtil.getTimeZoneOffsetMs();
public TriggerTimeRange() {
start = getMinSinceMidnight(DateUtil.now());
end = getMinSinceMidnight(DateUtil.now());
}
private TriggerTimeRange(TriggerTimeRange triggerTimeRange) {
super();
lastRun = triggerTimeRange.lastRun;
start = triggerTimeRange.start;
end = triggerTimeRange.end;
}
@Override
public boolean shouldRun() {
int currentMinSinceMidnight = getMinSinceMidnight(DateUtil.now());
if (lastRun > DateUtil.now() - T.mins(5).msecs())
return false;
boolean doRun = false;
if ( start < end && start < currentMinSinceMidnight && currentMinSinceMidnight < end)
doRun = true;
// handle cases like 10PM to 6AM
else if ( start > end && (start < currentMinSinceMidnight || currentMinSinceMidnight < end))
doRun = true;
if (doRun) {
if (L.isEnabled(L.AUTOMATION))
log.debug("Ready for execution: " + friendlyDescription());
return true;
}
return false;
}
@Override
public String toJSON() {
JSONObject object = new JSONObject();
JSONObject data = new JSONObject();
// check for too big values
if (start > 1440)
start = getMinSinceMidnight(start);
if (end > 1440)
end = getMinSinceMidnight(end);
try {
data.put("start", getMinSinceMidnight(start));
data.put("end", getMinSinceMidnight(end));
data.put("lastRun", lastRun);
object.put("type", TriggerTimeRange.class.getName());
object.put("data", data);
} catch (JSONException e) {
e.printStackTrace();
}
log.debug(object.toString());
return object.toString();
}
@Override
TriggerTimeRange fromJSON(String data) {
JSONObject o;
try {
o = new JSONObject(data);
lastRun = JsonHelper.safeGetLong(o, "lastRun");
start = JsonHelper.safeGetInt(o, "start");
end = JsonHelper.safeGetInt(o, "end");
} catch (JSONException e) {
e.printStackTrace();
}
return this;
}
@Override
public int friendlyName() {
return R.string.time_range;
}
@Override
public String friendlyDescription() {
return MainApp.gs(R.string.timerange_value, DateUtil.timeString(toMilis(start) - timeZoneOffset), DateUtil.timeString(toMilis(end) - timeZoneOffset));
}
@Override
public Optional<Integer> icon() {
return Optional.of(R.drawable.ic_access_alarm_24dp);
}
TriggerTimeRange period(int start, int end) {
this.start = getMinSinceMidnight(start*60000);
this.end = getMinSinceMidnight(end*60000);
return this;
}
TriggerTimeRange lastRun(long lastRun) {
this.lastRun = lastRun;
return this;
}
@Override
public Trigger duplicate() {
return new TriggerTimeRange(this);
}
long toMilis(long minutesSinceMidnight) {
return minutesSinceMidnight*60*1000;
}
public int getMinSinceMidnight(long time) {
// if passed argument is smaller than 1440 ( 24 h * 60 min ) that value is already converted
if (0 < time && time < 1441)
return (int) time;
Calendar calendar = DateUtil.gregorianCalendar();
calendar.setTimeInMillis(time);
return (calendar.get(Calendar.HOUR_OF_DAY) * 60) + calendar.get(Calendar.MINUTE);
}
int getStart(){
return start;
}
int getEnd(){
return end;
}
@Override
public void generateDialog(LinearLayout root, FragmentManager fragmentManager) {
TextView label = new TextView(root.getContext());
TextView startButton = new TextView(root.getContext());
TextView endButton = new TextView(root.getContext());
log.debug("Start is: " + start );
log.debug("End is: " + end );
startButton.setText(DateUtil.timeString(toMilis(start) - timeZoneOffset));
endButton.setText(MainApp.gs(R.string.and) + " " + DateUtil.timeString(toMilis(end) - timeZoneOffset));
startButton.setOnClickListener(view -> {
GregorianCalendar calendar = new GregorianCalendar();
//setTimeInMillis sets time in milliseconds after
// * January 1, 1970, 0:00:00 GMT., but our time contains timezone offsset
calendar.setTimeInMillis(toMilis(start) - timeZoneOffset);
TimePickerDialog tpd = TimePickerDialog.newInstance(
(view12, hourOfDay, minute, second) -> {
calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
calendar.set(Calendar.MINUTE, minute);
start = getMinSinceMidnight(calendar.getTimeInMillis());
startButton.setText(DateUtil.timeString(toMilis(start) - timeZoneOffset));
},
calendar.get(Calendar.HOUR_OF_DAY),
calendar.get(Calendar.MINUTE),
DateFormat.is24HourFormat(root.getContext())
);
tpd.setThemeDark(true);
tpd.dismissOnPause(true);
Activity a = scanForActivity(root.getContext());
if (a != null)
tpd.show(a.getFragmentManager(), "TimePickerDialog");
});
endButton.setOnClickListener(view -> {
GregorianCalendar calendar = new GregorianCalendar();
calendar.setTimeInMillis(toMilis(end) - timeZoneOffset);
TimePickerDialog tpd = TimePickerDialog.newInstance(
(view12, hourOfDay, minute, second) -> {
calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
calendar.set(Calendar.MINUTE, minute);
end = getMinSinceMidnight(calendar.getTimeInMillis());
endButton.setText(MainApp.gs(R.string.and) + " " + DateUtil.timeString(toMilis(end) - timeZoneOffset));
},
calendar.get(Calendar.HOUR_OF_DAY),
calendar.get(Calendar.MINUTE),
DateFormat.is24HourFormat(root.getContext())
);
tpd.setThemeDark(true);
tpd.dismissOnPause(true);
Activity a = scanForActivity(root.getContext());
if (a != null)
tpd.show(a.getFragmentManager(), "TimePickerDialog");
});
int px = MainApp.dpToPx(10);
label.setText(MainApp.gs(R.string.between));
label.setTypeface(label.getTypeface(), Typeface.BOLD);
startButton.setPadding(px, px, px, px);
endButton.setPadding(px, px, px, px);
LinearLayout l = new LinearLayout(root.getContext());
l.setOrientation(LinearLayout.HORIZONTAL);
l.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
l.addView(label);
l.addView(startButton);
l.addView(endButton);
root.addView(l);
}
}

View file

@ -296,7 +296,7 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
editSplit = (NumberPicker) view.findViewById(R.id.careportal_newnstreatment_splitinput);
editSplit.setParams(100d, 0d, 100d, 5d, new DecimalFormat("0"), true, view.findViewById(R.id.ok));
editDuration = (NumberPicker) view.findViewById(R.id.careportal_newnstreatment_durationinput);
editDuration.setParams(0d, 0d, 24 * 60d, 10d, new DecimalFormat("0"), false, view.findViewById(R.id.ok));
editDuration.setParams(0d, 0d, Constants.MAX_PROFILE_SWITCH_DURATION, 10d, new DecimalFormat("0"), false, view.findViewById(R.id.ok));
TextWatcher percentTextWatcher = new TextWatcher() {
@Override

View file

@ -3,6 +3,7 @@ package info.nightscout.androidaps.plugins.general.nsclient.data;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import androidx.annotation.Nullable;
import org.json.JSONException;
@ -16,12 +17,13 @@ import java.util.Objects;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.logging.BundleLogger;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.general.overview.OverviewPlugin;
import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification;
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification;
import info.nightscout.androidaps.logging.BundleLogger;
/*
{
@ -154,22 +156,22 @@ public class NSSettingsStatus {
try {
if (nsClientVersionCode < MainApp.instance().getPackageManager().getPackageInfo(MainApp.instance().getPackageName(), 0).versionCode) {
Notification notification = new Notification(Notification.OLD_NSCLIENT, MainApp.gs(R.string.unsupportedclientver), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(notification));
RxBus.INSTANCE.send(new EventNewNotification(notification));
} else {
MainApp.bus().post(new EventDismissNotification(Notification.OLD_NSCLIENT));
RxBus.INSTANCE.send(new EventDismissNotification(Notification.OLD_NSCLIENT));
}
} catch (PackageManager.NameNotFoundException e) {
log.error("Unhandled exception", e);
}
if (nightscoutVersionCode < Config.SUPPORTEDNSVERSION) {
Notification notification = new Notification(Notification.OLD_NS, MainApp.gs(R.string.unsupportednsversion), Notification.NORMAL);
MainApp.bus().post(new EventNewNotification(notification));
RxBus.INSTANCE.send(new EventNewNotification(notification));
} else {
MainApp.bus().post(new EventDismissNotification(Notification.OLD_NS));
RxBus.INSTANCE.send(new EventDismissNotification(Notification.OLD_NS));
}
} else {
Notification notification = new Notification(Notification.OLD_NSCLIENT, MainApp.gs(R.string.unsupportedclientver), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(notification));
RxBus.INSTANCE.send(new EventNewNotification(notification));
}
if (bundle.containsKey("status")) {
try {
@ -180,9 +182,9 @@ public class NSSettingsStatus {
Double targetHigh = getThreshold("bgTargetTop");
Double targetlow = getThreshold("bgTargetBottom");
if (targetHigh != null)
OverviewPlugin.bgTargetHigh = targetHigh;
OverviewPlugin.INSTANCE.setBgTargetHigh(targetHigh);
if (targetlow != null)
OverviewPlugin.bgTargetLow = targetlow;
OverviewPlugin.INSTANCE.setBgTargetLow(targetlow);
} catch (JSONException e) {
log.error("Unhandled exception", e);
}

View file

@ -35,6 +35,7 @@ import info.nightscout.androidaps.events.EventConfigBuilderChange;
import info.nightscout.androidaps.events.EventPreferenceChange;
import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.general.nsclient.NSClientPlugin;
import info.nightscout.androidaps.plugins.general.nsclient.UploadQueue;
import info.nightscout.androidaps.plugins.general.nsclient.acks.NSAddAck;
@ -177,7 +178,7 @@ public class NSClientService extends Service {
if (ev.isChanged(R.string.key_nsclientinternal_url) ||
ev.isChanged(R.string.key_nsclientinternal_api_secret) ||
ev.isChanged(R.string.key_nsclientinternal_paused)
) {
) {
latestDateInReceivedData = 0;
destroy();
initialize();
@ -269,7 +270,7 @@ public class NSClientService extends Service {
MainApp.bus().post(new EventNSClientNewLog("WATCHDOG", "connections in last " + WATCHDOG_INTERVAL_MINUTES + " mins: " + reconnections.size() + "/" + WATCHDOG_MAXCONNECTIONS));
if (reconnections.size() >= WATCHDOG_MAXCONNECTIONS) {
Notification n = new Notification(Notification.NSMALFUNCTION, MainApp.gs(R.string.nsmalfunction), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(n));
RxBus.INSTANCE.send(new EventNewNotification(n));
MainApp.bus().post(new EventNSClientNewLog("WATCHDOG", "pausing for " + WATCHDOG_RECONNECT_IN + " mins"));
NSClientPlugin.getPlugin().pause(true);
MainApp.bus().post(new EventNSClientUpdateGUI());
@ -347,9 +348,9 @@ public class NSClientService extends Service {
}
if (!hasWriteAuth) {
Notification noperm = new Notification(Notification.NSCLIENT_NO_WRITE_PERMISSION, MainApp.gs(R.string.nowritepermission), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(noperm));
RxBus.INSTANCE.send(new EventNewNotification(noperm));
} else {
MainApp.bus().post(new EventDismissNotification(Notification.NSCLIENT_NO_WRITE_PERMISSION));
RxBus.INSTANCE.send(new EventDismissNotification(Notification.NSCLIENT_NO_WRITE_PERMISSION));
}
}
@ -686,7 +687,7 @@ public class NSClientService extends Service {
if ((System.currentTimeMillis() - latestDateInReceivedData) / (60 * 1000L) < 15L)
lessThan15MinAgo = true;
if (Notification.isAlarmForStaleData() && lessThan15MinAgo) {
MainApp.bus().post(new EventDismissNotification(Notification.NSALARM));
RxBus.INSTANCE.send(new EventDismissNotification(Notification.NSALARM));
}
BroadcastSgvs.handleNewSgv(sgvs, MainApp.instance().getApplicationContext(), isDelta);
}

View file

@ -56,6 +56,7 @@ import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.data.QuickWizard;
import info.nightscout.androidaps.data.QuickWizardEntry;
import info.nightscout.androidaps.db.BgReading;
import info.nightscout.androidaps.db.DatabaseHelper;
@ -827,7 +828,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
final String profileName = ProfileFunctions.getInstance().getProfileName();
final PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump();
final QuickWizardEntry quickWizardEntry = OverviewPlugin.getPlugin().quickWizard.getActive();
final QuickWizardEntry quickWizardEntry = QuickWizard.INSTANCE.getActive();
if (quickWizardEntry != null && actualBg != null && profile != null && pump != null) {
quickWizardButton.setVisibility(View.VISIBLE);
final BolusWizard wizard = quickWizardEntry.doCalc(profile, profileName, actualBg, true);
@ -1008,7 +1009,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
timeView.setText(DateUtil.timeString(new Date()));
}
OverviewPlugin.getPlugin().notificationStore.updateNotifications(notificationsView);
OverviewPlugin.INSTANCE.getNotificationStore().updateNotifications(notificationsView);
pumpStatusLayout.setVisibility(View.GONE);
loopStatusLayout.setVisibility(View.GONE);
@ -1030,8 +1031,8 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
final String profileName = ProfileFunctions.getInstance().getProfileName();
final String units = profile.getUnits();
final double lowLine = OverviewPlugin.getPlugin().determineLowLine(units);
final double highLine = OverviewPlugin.getPlugin().determineHighLine(units);
final double lowLine = OverviewPlugin.INSTANCE.determineLowLine(units);
final double highLine = OverviewPlugin.INSTANCE.determineHighLine(units);
//Start with updating the BG as it is unaffected by loop.
// **** BG value ****
@ -1221,7 +1222,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
}
// QuickWizard button
QuickWizardEntry quickWizardEntry = OverviewPlugin.getPlugin().quickWizard.getActive();
QuickWizardEntry quickWizardEntry = QuickWizard.INSTANCE.getActive();
if (quickWizardEntry != null && lastBG != null && pump.isInitialized() && !pump.isSuspended()) {
quickWizardButton.setVisibility(View.VISIBLE);
String text = quickWizardEntry.buttonText() + "\n" + DecimalFormatter.to0Decimal(quickWizardEntry.carbs()) + "g";

View file

@ -1,111 +0,0 @@
package info.nightscout.androidaps.plugins.general.overview;
import com.squareup.otto.Subscribe;
import org.json.JSONArray;
import org.json.JSONException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.data.QuickWizard;
import info.nightscout.androidaps.events.EventRefreshOverview;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginDescription;
import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification;
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.general.overview.notifications.NotificationStore;
import info.nightscout.androidaps.utils.SP;
/**
* Created by mike on 05.08.2016.
*/
public class OverviewPlugin extends PluginBase {
private static Logger log = LoggerFactory.getLogger(L.OVERVIEW);
private static OverviewPlugin overviewPlugin = new OverviewPlugin();
public static OverviewPlugin getPlugin() {
if (overviewPlugin == null)
overviewPlugin = new OverviewPlugin();
return overviewPlugin;
}
public static double bgTargetLow = 80d;
public static double bgTargetHigh = 180d;
public QuickWizard quickWizard = new QuickWizard();
public NotificationStore notificationStore = new NotificationStore();
public OverviewPlugin() {
super(new PluginDescription()
.mainType(PluginType.GENERAL)
.fragmentClass(OverviewFragment.class.getName())
.alwaysVisible(true)
.alwaysEnabled(true)
.pluginName(R.string.overview)
.shortName(R.string.overview_shortname)
.preferencesId(R.xml.pref_overview)
.description(R.string.description_overview)
);
String storedData = SP.getString("QuickWizard", "[]");
try {
quickWizard.setData(new JSONArray(storedData));
} catch (JSONException e) {
log.error("Unhandled exception", e);
}
}
@Override
protected void onStart() {
MainApp.bus().register(this);
super.onStart();
}
@Override
protected void onStop() {
MainApp.bus().unregister(this);
super.onStop();
}
@Subscribe
public void onStatusEvent(final EventNewNotification n) {
if (notificationStore.add(n.notification))
MainApp.bus().post(new EventRefreshOverview("EventNewNotification"));
}
@Subscribe
public void onStatusEvent(final EventDismissNotification n) {
if (notificationStore.remove(n.id))
MainApp.bus().post(new EventRefreshOverview("EventDismissNotification"));
}
public double determineHighLine(String units) {
double highLineSetting = SP.getDouble("high_mark", Profile.fromMgdlToUnits(OverviewPlugin.bgTargetHigh, units));
if (highLineSetting < 1)
highLineSetting = Profile.fromMgdlToUnits(180d, units);
return highLineSetting;
}
public double determineLowLine() {
Profile profile = ProfileFunctions.getInstance().getProfile();
if (profile == null) {
return bgTargetLow;
}
return determineLowLine(profile.getUnits());
}
public double determineLowLine(String units) {
double lowLineSetting = SP.getDouble("low_mark", Profile.fromMgdlToUnits(OverviewPlugin.bgTargetLow, units));
if (lowLineSetting < 1)
lowLineSetting = Profile.fromMgdlToUnits(76d, units);
return lowLineSetting;
}
}

View file

@ -0,0 +1,86 @@
package info.nightscout.androidaps.plugins.general.overview
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R
import info.nightscout.androidaps.data.Profile
import info.nightscout.androidaps.events.EventRefreshOverview
import info.nightscout.androidaps.interfaces.PluginBase
import info.nightscout.androidaps.interfaces.PluginDescription
import info.nightscout.androidaps.interfaces.PluginType
import info.nightscout.androidaps.logging.L
import info.nightscout.androidaps.plugins.bus.RxBus
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions
import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification
import info.nightscout.androidaps.plugins.general.overview.notifications.NotificationStore
import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.SP
import info.nightscout.androidaps.utils.plusAssign
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
import org.slf4j.LoggerFactory
object OverviewPlugin : PluginBase(PluginDescription()
.mainType(PluginType.GENERAL)
.fragmentClass(OverviewFragment::class.qualifiedName)
.alwaysVisible(true)
.alwaysEnabled(true)
.pluginName(R.string.overview)
.shortName(R.string.overview_shortname)
.preferencesId(R.xml.pref_overview)
.description(R.string.description_overview)) {
private val log = LoggerFactory.getLogger(L.OVERVIEW)
private var disposable: CompositeDisposable = CompositeDisposable()
var bgTargetLow = 80.0
var bgTargetHigh = 180.0
var notificationStore = NotificationStore()
override fun onStart() {
super.onStart()
disposable += RxBus
.toObservable(EventNewNotification::class.java)
.observeOn(Schedulers.io())
.subscribe({ n ->
if (notificationStore.add(n.notification))
MainApp.bus().post(EventRefreshOverview("EventNewNotification"))
}, {
FabricPrivacy.logException(it)
})
disposable += RxBus
.toObservable(EventDismissNotification::class.java)
.observeOn(Schedulers.io())
.subscribe({ n ->
if (notificationStore.remove(n.id))
MainApp.bus().post(EventRefreshOverview("EventDismissNotification"))
}, {
FabricPrivacy.logException(it)
})
}
override fun onStop() {
disposable.clear()
super.onStop()
}
fun determineHighLine(units: String): Double {
var highLineSetting = SP.getDouble("high_mark", Profile.fromMgdlToUnits(bgTargetHigh, units))!!
if (highLineSetting < 1)
highLineSetting = Profile.fromMgdlToUnits(180.0, units)
return highLineSetting
}
fun determineLowLine(): Double {
val profile = ProfileFunctions.getInstance().profile ?: return bgTargetLow
return determineLowLine(profile.units)
}
fun determineLowLine(units: String): Double {
var lowLineSetting = SP.getDouble("low_mark", Profile.fromMgdlToUnits(bgTargetLow, units))!!
if (lowLineSetting < 1)
lowLineSetting = Profile.fromMgdlToUnits(76.0, units)
return lowLineSetting
}
}

View file

@ -1,173 +0,0 @@
package info.nightscout.androidaps.plugins.general.overview.activities;
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import androidx.cardview.widget.CardView;
import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.squareup.otto.Subscribe;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.activities.NoSplashAppCompatActivity;
import info.nightscout.androidaps.data.QuickWizard;
import info.nightscout.androidaps.plugins.general.overview.OverviewPlugin;
import info.nightscout.androidaps.plugins.general.overview.dialogs.EditQuickWizardDialog;
import info.nightscout.androidaps.plugins.general.overview.events.EventQuickWizardChange;
import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.DecimalFormatter;
public class QuickWizardListActivity extends NoSplashAppCompatActivity implements View.OnClickListener {
RecyclerView recyclerView;
LinearLayoutManager llm;
Button adButton;
public static class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.QuickWizardEntryViewHolder> {
QuickWizard qvData;
FragmentManager fragmentManager;
RecyclerViewAdapter(QuickWizard data, FragmentManager fragmentManager) {
this.qvData = data;
this.fragmentManager = fragmentManager;
}
@Override
public QuickWizardEntryViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.overview_quickwizardlist_item, viewGroup, false);
QuickWizardEntryViewHolder quickWizardEntryViewHolder = new QuickWizardEntryViewHolder(v, fragmentManager, qvData);
return quickWizardEntryViewHolder;
}
@Override
public void onBindViewHolder(QuickWizardEntryViewHolder holder, int position) {
holder.from.setText(DateUtil.timeString(qvData.get(position).validFromDate()));
holder.to.setText(DateUtil.timeString(qvData.get(position).validToDate()));
holder.buttonText.setText(qvData.get(position).buttonText());
holder.carbs.setText(DecimalFormatter.to0Decimal(qvData.get(position).carbs()) + " g");
}
@Override
public int getItemCount() {
return qvData.size();
}
@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
public static class QuickWizardEntryViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
CardView cv;
TextView buttonText;
TextView carbs;
TextView from;
TextView to;
Button editButton;
Button removeButton;
FragmentManager fragmentManager;
QuickWizard qvData;
QuickWizardEntryViewHolder(View itemView, FragmentManager fragmentManager, QuickWizard qvData) {
super(itemView);
cv = (CardView) itemView.findViewById(R.id.overview_quickwizard_cardview);
buttonText = (TextView) itemView.findViewById(R.id.overview_quickwizard_item_buttonText);
carbs = (TextView) itemView.findViewById(R.id.overview_quickwizard_item_carbs);
from = (TextView) itemView.findViewById(R.id.overview_quickwizard_item_from);
to = (TextView) itemView.findViewById(R.id.overview_quickwizard_item_to);
editButton = (Button) itemView.findViewById(R.id.overview_quickwizard_item_edit_button);
removeButton = (Button) itemView.findViewById(R.id.overview_quickwizard_item_remove_button);
editButton.setOnClickListener(this);
removeButton.setOnClickListener(this);
this.fragmentManager = fragmentManager;
this.qvData = qvData;
}
@Override
public void onClick(View v) {
int position = getAdapterPosition();
switch (v.getId()) {
case R.id.overview_quickwizard_item_edit_button:
FragmentManager manager = fragmentManager;
EditQuickWizardDialog editQuickWizardDialog = new EditQuickWizardDialog();
editQuickWizardDialog.setData(qvData.get(position));
editQuickWizardDialog.show(manager, "EditQuickWizardDialog");
break;
case R.id.overview_quickwizard_item_remove_button:
qvData.remove(position);
MainApp.bus().post(new EventQuickWizardChange());
break;
}
}
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.overview_quickwizardlist_activity);
recyclerView = (RecyclerView) findViewById(R.id.overview_quickwizardactivity_recyclerview);
recyclerView.setHasFixedSize(true);
llm = new LinearLayoutManager(this);
recyclerView.setLayoutManager(llm);
RecyclerViewAdapter adapter = new RecyclerViewAdapter(MainApp.getSpecificPlugin(OverviewPlugin.class).quickWizard, getSupportFragmentManager());
recyclerView.setAdapter(adapter);
adButton = (Button) findViewById(R.id.overview_quickwizardactivity_add_button);
adButton.setOnClickListener(this);
}
@Override
protected void onResume() {
super.onResume();
MainApp.bus().register(this);
}
@Override
protected void onPause() {
super.onPause();
MainApp.bus().unregister(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.overview_quickwizardactivity_add_button:
FragmentManager manager = getSupportFragmentManager();
EditQuickWizardDialog editQuickWizardDialog = new EditQuickWizardDialog();
editQuickWizardDialog.show(manager, "EditQuickWizardDialog");
break;
}
}
@Subscribe
public void onStatusEvent(final EventQuickWizardChange ev) {
updateGUI();
}
public void updateGUI() {
Activity activity = this;
if (activity != null && recyclerView != null) {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
RecyclerViewAdapter adapter = new RecyclerViewAdapter(MainApp.getSpecificPlugin(OverviewPlugin.class).quickWizard, getSupportFragmentManager());
recyclerView.swapAdapter(adapter, false);
}
});
}
}
}

View file

@ -0,0 +1,100 @@
package info.nightscout.androidaps.plugins.general.overview.activities
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import androidx.fragment.app.FragmentManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import info.nightscout.androidaps.R
import info.nightscout.androidaps.activities.NoSplashAppCompatActivity
import info.nightscout.androidaps.data.QuickWizard
import info.nightscout.androidaps.plugins.bus.RxBus
import info.nightscout.androidaps.plugins.general.overview.dialogs.EditQuickWizardDialog
import info.nightscout.androidaps.plugins.general.overview.events.EventQuickWizardChange
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.DecimalFormatter
import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.plusAssign
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import kotlinx.android.synthetic.main.overview_quickwizardlist_activity.*
class QuickWizardListActivity : NoSplashAppCompatActivity() {
private var disposable: CompositeDisposable = CompositeDisposable()
private inner class RecyclerViewAdapter internal constructor(internal var fragmentManager: FragmentManager) : RecyclerView.Adapter<RecyclerViewAdapter.QuickWizardEntryViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): QuickWizardEntryViewHolder {
return QuickWizardEntryViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.overview_quickwizardlist_item, parent, false), fragmentManager)
}
override fun onBindViewHolder(holder: QuickWizardEntryViewHolder, position: Int) {
holder.from.text = DateUtil.timeString(QuickWizard[position].validFromDate())
holder.to.text = DateUtil.timeString(QuickWizard[position].validToDate())
holder.buttonText.text = QuickWizard[position].buttonText()
holder.carbs.text = DecimalFormatter.to0Decimal(QuickWizard[position].carbs().toDouble()) + " g"
}
override fun getItemCount(): Int = QuickWizard.size()
private inner class QuickWizardEntryViewHolder internal constructor(itemView: View, internal var fragmentManager: FragmentManager) : RecyclerView.ViewHolder(itemView) {
val buttonText: TextView = itemView.findViewById(R.id.overview_quickwizard_item_buttonText)
val carbs: TextView = itemView.findViewById(R.id.overview_quickwizard_item_carbs)
val from: TextView = itemView.findViewById(R.id.overview_quickwizard_item_from)
val to: TextView = itemView.findViewById(R.id.overview_quickwizard_item_to)
private val editButton: Button = itemView.findViewById(R.id.overview_quickwizard_item_edit_button)
private val removeButton: Button = itemView.findViewById(R.id.overview_quickwizard_item_remove_button)
init {
editButton.setOnClickListener {
val manager = fragmentManager
val editQuickWizardDialog = EditQuickWizardDialog()
editQuickWizardDialog.entry = QuickWizard[adapterPosition]
editQuickWizardDialog.show(manager, "EditQuickWizardDialog")
}
removeButton.setOnClickListener {
QuickWizard.remove(adapterPosition)
RxBus.send(EventQuickWizardChange())
}
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.overview_quickwizardlist_activity)
overview_quickwizardactivity_recyclerview?.setHasFixedSize(true)
overview_quickwizardactivity_recyclerview?.layoutManager = LinearLayoutManager(this)
overview_quickwizardactivity_recyclerview?.adapter = RecyclerViewAdapter(supportFragmentManager)
overview_quickwizardactivity_add_button.setOnClickListener {
val manager = supportFragmentManager
val editQuickWizardDialog = EditQuickWizardDialog()
editQuickWizardDialog.show(manager, "EditQuickWizardDialog")
}
}
override fun onResume() {
super.onResume()
disposable += RxBus
.toObservable(EventQuickWizardChange::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
val adapter = RecyclerViewAdapter(supportFragmentManager)
overview_quickwizardactivity_recyclerview?.swapAdapter(adapter, false)
}, {
FabricPrivacy.logException(it)
})
}
override fun onPause() {
disposable.clear()
super.onPause()
}
}

View file

@ -1,216 +0,0 @@
package info.nightscout.androidaps.plugins.general.overview.dialogs;
import android.os.Bundle;
import androidx.fragment.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import org.json.JSONException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.QuickWizard;
import info.nightscout.androidaps.data.QuickWizardEntry;
import info.nightscout.androidaps.plugins.general.overview.OverviewPlugin;
import info.nightscout.androidaps.plugins.general.overview.events.EventQuickWizardChange;
import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.SafeParse;
public class EditQuickWizardDialog extends DialogFragment implements View.OnClickListener {
private static Logger log = LoggerFactory.getLogger(EditQuickWizardDialog.class);
QuickWizardEntry entry = new QuickWizard().newEmptyItem();
QuickWizard quickWizard = MainApp.getSpecificPlugin(OverviewPlugin.class).quickWizard;
EditText buttonEdit;
EditText carbsEdit;
Spinner fromSpinner;
Spinner toSpinner;
Spinner useBGSpinner;
Spinner useCOBSpinner;
Spinner useBolusIOBSpinner;
Spinner useBasalIOBSpinner;
Spinner useTrendSpinner;
Spinner useSuperBolusSpinner;
Spinner useTempTargetSpinner;
public EditQuickWizardDialog() {
}
public void setData(QuickWizardEntry data) {
entry = data;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
View view = inflater.inflate(R.layout.overview_editquickwizard_dialog, container, false);
buttonEdit = view.findViewById(R.id.overview_editquickwizard_button_edit);
carbsEdit = view.findViewById(R.id.overview_editquickwizard_carbs_edit);
fromSpinner = view.findViewById(R.id.overview_editquickwizard_from_spinner);
toSpinner = view.findViewById(R.id.overview_editquickwizard_to_spinner);
useBGSpinner = view.findViewById(R.id.overview_editquickwizard_usebg_spinner);
useCOBSpinner = view.findViewById(R.id.overview_editquickwizard_usecob_spinner);
useBolusIOBSpinner = view.findViewById(R.id.overview_editquickwizard_usebolusiob_spinner);
useBasalIOBSpinner = view.findViewById(R.id.overview_editquickwizard_usebasaliob_spinner);
useTrendSpinner = view.findViewById(R.id.overview_editquickwizard_usetrend_spinner);
useSuperBolusSpinner = view.findViewById(R.id.overview_editquickwizard_usesuperbolus_spinner);
useTempTargetSpinner = view.findViewById(R.id.overview_editquickwizard_usetemptarget_spinner);
view.findViewById(R.id.ok).setOnClickListener(this);
view.findViewById(R.id.cancel).setOnClickListener(this);
int posFrom = 0;
int posTo = 95;
ArrayList<CharSequence> timeList = new ArrayList<>();
int pos = 0;
for (int t = 0; t < 24 * 60 * 60; t += 15 * 60) {
timeList.add(DateUtil.timeString(DateUtil.toDate(t)));
if (entry.validFrom() == t) posFrom = pos;
if (entry.validTo() == t) posTo = pos;
pos++;
}
timeList.add(DateUtil.timeString(DateUtil.toDate(24 * 60 * 60 - 60)));
ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(getContext(),
R.layout.spinner_centered, timeList);
fromSpinner.setAdapter(adapter);
toSpinner.setAdapter(adapter);
buttonEdit.setText(entry.buttonText());
carbsEdit.setText(entry.carbs().toString());
fromSpinner.setSelection(posFrom);
toSpinner.setSelection(posTo);
setSelection(useBGSpinner, entry.useBG());
setSelection(useCOBSpinner, entry.useCOB());
setSelection(useBolusIOBSpinner, entry.useBolusIOB());
setSelection(useBasalIOBSpinner, entry.useBasalIOB());
setSelection(useTrendSpinner, entry.useTrend());
setSelection(useSuperBolusSpinner, entry.useSuperBolus());
setSelection(useTempTargetSpinner, entry.useTempTarget());
useCOBSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
processCob();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
processCob();
return view;
}
@Override
public void onResume() {
super.onResume();
if (getDialog() != null)
getDialog().getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.ok:
if (fromSpinner.getSelectedItem() == null) return;
if (toSpinner.getSelectedItem() == null) return;
try {
entry.storage.put("buttonText", buttonEdit.getText().toString());
entry.storage.put("carbs", SafeParse.stringToInt(carbsEdit.getText().toString()));
int validFromInt = DateUtil.toSeconds(fromSpinner.getSelectedItem().toString());
entry.storage.put("validFrom", validFromInt);
int validToInt = DateUtil.toSeconds(toSpinner.getSelectedItem().toString());
entry.storage.put("validTo", validToInt);
entry.storage.put("useBG", getSelection(useBGSpinner));
entry.storage.put("useCOB", getSelection(useCOBSpinner));
entry.storage.put("useBolusIOB", getSelection(useBolusIOBSpinner));
entry.storage.put("useBasalIOB", getSelection(useBasalIOBSpinner));
entry.storage.put("useTrend", getSelection(useTrendSpinner));
entry.storage.put("useSuperBolus", getSelection(useSuperBolusSpinner));
entry.storage.put("useTempTarget", getSelection(useTempTargetSpinner));
} catch (JSONException e) {
log.error("Unhandled exception", e);
}
quickWizard.addOrUpdate(entry);
dismiss();
MainApp.bus().post(new EventQuickWizardChange());
break;
case R.id.cancel:
dismiss();
break;
}
}
private void processCob() {
if (getSelection(useCOBSpinner) == QuickWizardEntry.YES) {
useBolusIOBSpinner.setEnabled(false);
useBasalIOBSpinner.setEnabled(false);
setSelection(useBolusIOBSpinner, QuickWizardEntry.YES);
setSelection(useBasalIOBSpinner, QuickWizardEntry.YES);
} else {
useBolusIOBSpinner.setEnabled(true);
useBasalIOBSpinner.setEnabled(true);
}
}
int getSelection(Spinner spinner) {
String value = spinner.getSelectedItem().toString();
if (value.equals(MainApp.gs(R.string.yes)))
return QuickWizardEntry.YES;
if (value.equals(MainApp.gs(R.string.no)))
return QuickWizardEntry.NO;
if (value.equals(MainApp.gs(R.string.positiveonly)))
return QuickWizardEntry.POSITIVE_ONLY;
if (value.equals(MainApp.gs(R.string.negativeonly)))
return QuickWizardEntry.NEGATIVE_ONLY;
return QuickWizardEntry.NO;
}
void setSelection(Spinner spinner, int value) {
String selection;
switch (value) {
case QuickWizardEntry.YES:
selection = MainApp.gs(R.string.yes);
break;
case QuickWizardEntry.NO:
selection = MainApp.gs(R.string.no);
break;
case QuickWizardEntry.POSITIVE_ONLY:
selection = MainApp.gs(R.string.positiveonly);
break;
case QuickWizardEntry.NEGATIVE_ONLY:
selection = MainApp.gs(R.string.negativeonly);
break;
default:
selection = MainApp.gs(R.string.no);
break;
}
for (int i = 0; i < spinner.getCount(); i++) {
if (spinner.getItemAtPosition(i).toString().equalsIgnoreCase(selection)) {
spinner.setSelection(i);
break;
}
}
}
}

View file

@ -0,0 +1,118 @@
package info.nightscout.androidaps.plugins.general.overview.dialogs
import android.os.Bundle
import android.view.*
import android.widget.AdapterView
import android.widget.ArrayAdapter
import androidx.fragment.app.DialogFragment
import info.nightscout.androidaps.R
import info.nightscout.androidaps.data.QuickWizard
import info.nightscout.androidaps.data.QuickWizardEntry
import info.nightscout.androidaps.plugins.bus.RxBus
import info.nightscout.androidaps.plugins.general.overview.events.EventQuickWizardChange
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.SafeParse
import kotlinx.android.synthetic.main.okcancel.*
import kotlinx.android.synthetic.main.overview_editquickwizard_dialog.*
import org.json.JSONException
import org.slf4j.LoggerFactory
import java.util.*
class EditQuickWizardDialog : DialogFragment() {
private val log = LoggerFactory.getLogger(EditQuickWizardDialog::class.java)
internal var entry = QuickWizard.newEmptyItem()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
dialog?.window?.requestFeature(Window.FEATURE_NO_TITLE)
dialog?.window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN)
isCancelable = true
dialog?.setCanceledOnTouchOutside(false)
return inflater.inflate(R.layout.overview_editquickwizard_dialog, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
ok.setOnClickListener {
if (overview_editquickwizard_from_spinner.selectedItem == null) return@setOnClickListener
if (overview_editquickwizard_to_spinner.selectedItem == null) return@setOnClickListener
try {
entry.storage.put("buttonText", overview_editquickwizard_button_edit.text.toString())
entry.storage.put("carbs", SafeParse.stringToInt(overview_editquickwizard_carbs_edit.text.toString()))
val validFromInt = DateUtil.toSeconds(overview_editquickwizard_from_spinner.selectedItem.toString())
entry.storage.put("validFrom", validFromInt)
val validToInt = DateUtil.toSeconds(overview_editquickwizard_to_spinner.selectedItem.toString())
entry.storage.put("validTo", validToInt)
entry.storage.put("useBG", overview_editquickwizard_usebg_spinner.selectedItemPosition)
entry.storage.put("useCOB", overview_editquickwizard_usecob_spinner.selectedItemPosition)
entry.storage.put("useBolusIOB", overview_editquickwizard_usebolusiob_spinner.selectedItemPosition)
entry.storage.put("useBasalIOB", overview_editquickwizard_usebasaliob_spinner.selectedItemPosition)
entry.storage.put("useTrend", overview_editquickwizard_usetrend_spinner.selectedItemPosition)
entry.storage.put("useSuperBolus", overview_editquickwizard_usesuperbolus_spinner.selectedItemPosition)
entry.storage.put("useTempTarget", overview_editquickwizard_usetemptarget_spinner.selectedItemPosition)
} catch (e: JSONException) {
log.error("Unhandled exception", e)
}
QuickWizard.addOrUpdate(entry)
RxBus.send(EventQuickWizardChange())
dismiss()
}
cancel.setOnClickListener { dismiss() }
var posFrom = 0
var posTo = 95
val timeList = ArrayList<CharSequence>()
var pos = 0
var t = 0
while (t < 24 * 60 * 60) {
timeList.add(DateUtil.timeString(DateUtil.toDate(t)))
if (entry.validFrom() == t) posFrom = pos
if (entry.validTo() == t) posTo = pos
pos++
t += 15 * 60
}
timeList.add(DateUtil.timeString(DateUtil.toDate(24 * 60 * 60 - 60)))
val adapter = context?.let { context -> ArrayAdapter(context, R.layout.spinner_centered, timeList) }
overview_editquickwizard_from_spinner.adapter = adapter
overview_editquickwizard_to_spinner.adapter = adapter
overview_editquickwizard_button_edit.setText(entry.buttonText())
overview_editquickwizard_carbs_edit.setText(entry.carbs().toString())
overview_editquickwizard_from_spinner.setSelection(posFrom)
overview_editquickwizard_to_spinner.setSelection(posTo)
overview_editquickwizard_usebg_spinner.setSelection(entry.useBG())
overview_editquickwizard_usecob_spinner.setSelection(entry.useCOB())
overview_editquickwizard_usebolusiob_spinner.setSelection(entry.useBolusIOB())
overview_editquickwizard_usebasaliob_spinner.setSelection(entry.useBasalIOB())
overview_editquickwizard_usetrend_spinner.setSelection(entry.useTrend())
overview_editquickwizard_usesuperbolus_spinner.setSelection(entry.useSuperBolus())
overview_editquickwizard_usetemptarget_spinner.setSelection(entry.useTempTarget())
overview_editquickwizard_usecob_spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) = processCob()
override fun onNothingSelected(parent: AdapterView<*>) {}
}
processCob()
}
override fun onResume() {
super.onResume()
dialog?.window?.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
}
private fun processCob() {
if (overview_editquickwizard_usecob_spinner.selectedItemPosition == QuickWizardEntry.YES) {
overview_editquickwizard_usebolusiob_spinner.isEnabled = false
overview_editquickwizard_usebasaliob_spinner.isEnabled = false
overview_editquickwizard_usebolusiob_spinner.setSelection(QuickWizardEntry.YES)
overview_editquickwizard_usebasaliob_spinner.setSelection(QuickWizardEntry.YES)
} else {
overview_editquickwizard_usebolusiob_spinner.isEnabled = true
overview_editquickwizard_usebasaliob_spinner.isEnabled = true
}
}
}

View file

@ -1,16 +0,0 @@
package info.nightscout.androidaps.plugins.general.overview.events;
import info.nightscout.androidaps.events.Event;
/**
* Created by mike on 03.12.2016.
*/
public class EventDismissNotification extends Event {
public int id;
public EventDismissNotification(int did) {
id = did;
}
}

View file

@ -0,0 +1,5 @@
package info.nightscout.androidaps.plugins.general.overview.events
import info.nightscout.androidaps.events.Event
class EventDismissNotification(var id: Int) : Event()

View file

@ -1,16 +0,0 @@
package info.nightscout.androidaps.plugins.general.overview.events;
import info.nightscout.androidaps.events.Event;
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification;
/**
* Created by mike on 03.12.2016.
*/
public class EventNewNotification extends Event {
public Notification notification;
public EventNewNotification(Notification n) {
notification = n;
}
}

View file

@ -0,0 +1,6 @@
package info.nightscout.androidaps.plugins.general.overview.events
import info.nightscout.androidaps.events.Event
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification
class EventNewNotification(var notification: Notification) : Event()

View file

@ -1,10 +0,0 @@
package info.nightscout.androidaps.plugins.general.overview.events;
import info.nightscout.androidaps.events.Event;
/**
* Created by mike on 20.10.2016.
*/
public class EventQuickWizardChange extends Event {
}

View file

@ -0,0 +1,5 @@
package info.nightscout.androidaps.plugins.general.overview.events
import info.nightscout.androidaps.events.Event
class EventQuickWizardChange : Event()

View file

@ -3,9 +3,11 @@ package info.nightscout.androidaps.plugins.general.overview.notifications;
import android.app.IntentService;
import android.app.PendingIntent;
import android.content.Intent;
import androidx.annotation.Nullable;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification;
public class DismissNotificationService extends IntentService {
@ -19,16 +21,16 @@ public class DismissNotificationService extends IntentService {
super(name);
}
public DismissNotificationService(){
public DismissNotificationService() {
super("DismissNotificationService");
}
@Override
protected void onHandleIntent(@Nullable Intent intent) {
MainApp.bus().post(new EventDismissNotification(intent.getIntExtra("alertID", -1)));
RxBus.INSTANCE.send(new EventDismissNotification(intent.getIntExtra("alertID", -1)));
}
public static PendingIntent deleteIntent(int id){
public static PendingIntent deleteIntent(int id) {
Intent intent = new Intent(MainApp.instance(), DismissNotificationService.class);
intent.putExtra("alertID", id);
return PendingIntent.getService(MainApp.instance(), id, intent, PendingIntent.FLAG_UPDATE_CURRENT);

View file

@ -20,6 +20,7 @@ import java.util.Objects;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.general.nsclient.broadcasts.BroadcastAckAlarm;
import info.nightscout.androidaps.plugins.general.overview.OverviewPlugin;
import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification;
@ -90,7 +91,7 @@ public class NotificationRecyclerViewAdapter extends RecyclerView.Adapter<Notifi
@Override
public void onClick(View v) {
Notification notification = (Notification) v.getTag();
MainApp.bus().post(new EventDismissNotification(notification.id));
RxBus.INSTANCE.send(new EventDismissNotification(notification.id));
if (notification.nsAlarm != null) {
BroadcastAckAlarm.handleClearAlarm(notification.nsAlarm, MainApp.instance().getApplicationContext(), 60 * 60 * 1000L);
}
@ -98,7 +99,7 @@ public class NotificationRecyclerViewAdapter extends RecyclerView.Adapter<Notifi
if (L.isEnabled(L.NOTIFICATION))
log.debug("Notification text is: " + notification.text);
if (notification.text.equals(MainApp.gs(R.string.nsalarm_staledata))) {
NotificationStore nstore = OverviewPlugin.getPlugin().notificationStore;
NotificationStore nstore = OverviewPlugin.INSTANCE.getNotificationStore();
long msToSnooze = SP.getInt("nsalarm_staledatavalue", 15) * 60 * 1000L;
if (L.isEnabled(L.NOTIFICATION))
log.debug("snooze nsalarm_staledatavalue in minutes is " + SP.getInt("nsalarm_staledatavalue", 15) + "\n in ms is: " + msToSnooze + " currentTimeMillis is: " + System.currentTimeMillis());

View file

@ -32,6 +32,7 @@ import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginDescription;
import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification;
import info.nightscout.androidaps.utils.SP;
@ -103,7 +104,7 @@ public class SignatureVerifier extends PluginBase implements ConstraintsInterfac
private void showNotification() {
Notification notification = new Notification(Notification.INVALID_VERSION, MainApp.gs(R.string.running_invalid_version), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(notification));
RxBus.INSTANCE.send(new EventNewNotification(notification));
}
private boolean hasIllegalSignature() {
@ -147,7 +148,7 @@ public class SignatureVerifier extends PluginBase implements ConstraintsInterfac
private void loadLocalRevokedCerts() {
try {
String revokedCerts = readCachedDownloadedRevokedCerts();
if (revokedCerts == null) revokedCerts = readRevokedCertsInAssets();
if (revokedCerts == null) revokedCerts = readRevokedCertsInAssets();
synchronized ($lock) {
this.revokedCerts = parseRevokedCertsFile(revokedCerts);
}

View file

@ -35,6 +35,7 @@ import info.nightscout.androidaps.interfaces.ProfileInterface;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin;
import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload;
@ -106,9 +107,8 @@ public class SmsCommunicatorPlugin extends PluginBase {
if (ev == null || ev.isChanged(R.string.key_smscommunicator_allowednumbers)) {
String settings = SP.getString(R.string.key_smscommunicator_allowednumbers, "");
String pattern = ";";
String[] substrings = settings.split(pattern);
allowedNumbers.clear();
String[] substrings = settings.split(";");
for (String number : substrings) {
String cleaned = number.replaceAll("\\s+", "");
allowedNumbers.add(cleaned);
@ -769,10 +769,10 @@ public class SmsCommunicatorPlugin extends PluginBase {
messages.add(sms);
} catch (IllegalArgumentException e) {
Notification notification = new Notification(Notification.INVALID_PHONE_NUMBER, MainApp.gs(R.string.smscommunicator_invalidphonennumber), Notification.NORMAL);
MainApp.bus().post(new EventNewNotification(notification));
RxBus.INSTANCE.send(new EventNewNotification(notification));
} catch (java.lang.SecurityException e) {
Notification notification = new Notification(Notification.MISSING_SMS_PERMISSION, MainApp.gs(R.string.smscommunicator_missingsmspermission), Notification.NORMAL);
MainApp.bus().post(new EventNewNotification(notification));
RxBus.INSTANCE.send(new EventNewNotification(notification));
}
MainApp.bus().post(new EventSmsCommunicatorUpdateGui());
}

View file

@ -3,6 +3,7 @@ package info.nightscout.androidaps.plugins.general.versionChecker
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R
import info.nightscout.androidaps.interfaces.*
import info.nightscout.androidaps.plugins.bus.RxBus
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification
import info.nightscout.androidaps.utils.SP
@ -46,7 +47,7 @@ object VersionCheckerPlugin : PluginBase(PluginDescription()
//notify
val message = MainApp.gs(R.string.new_version_warning, Math.round((now - SP.getLong(R.string.key_last_time_this_version_detected, now)) / TimeUnit.DAYS.toMillis(1).toDouble()))
val notification = Notification(Notification.OLDVERSION, message, Notification.NORMAL)
MainApp.bus().post(EventNewNotification(notification))
RxBus.send(EventNewNotification(notification))
}
}

View file

@ -6,6 +6,7 @@ import info.nightscout.androidaps.BuildConfig
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R
import info.nightscout.androidaps.logging.L
import info.nightscout.androidaps.plugins.bus.RxBus
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification
import info.nightscout.androidaps.utils.SP
@ -82,7 +83,7 @@ fun onNewVersionDetected(currentVersion: String, newVersion: String?) {
if (now > SP.getLong(R.string.key_last_versionchecker_warning, 0) + WARN_EVERY) {
log.debug("Version ${currentVersion} outdated. Found $newVersion")
val notification = Notification(Notification.NEWVERSIONDETECTED, String.format(MainApp.gs(R.string.versionavailable), newVersion.toString()), Notification.LOW)
MainApp.bus().post(EventNewNotification(notification))
RxBus.send(EventNewNotification(notification))
SP.putLong(R.string.key_last_versionchecker_warning, now)
}
}

View file

@ -2,7 +2,7 @@ package info.nightscout.androidaps.plugins.general.wear;
import android.app.NotificationManager;
import android.content.Context;
import android.os.HandlerThread;
import androidx.annotation.NonNull;
import java.text.DateFormat;
@ -31,15 +31,15 @@ import info.nightscout.androidaps.interfaces.APSInterface;
import info.nightscout.androidaps.interfaces.Constraint;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.plugins.general.actions.dialogs.FillDialog;
import info.nightscout.androidaps.plugins.general.careportal.Dialogs.NewNSTreatmentDialog;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.CobInfo;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin;
import info.nightscout.androidaps.plugins.aps.loop.APSResult;
import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin;
import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.general.careportal.Dialogs.NewNSTreatmentDialog;
import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.CobInfo;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin;
import info.nightscout.androidaps.plugins.pump.danaR.DanaRPlugin;
import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump;
import info.nightscout.androidaps.plugins.pump.danaRKorean.DanaRKoreanPlugin;
@ -214,7 +214,7 @@ public class ActionStringHandler {
}
CobInfo cobInfo = IobCobCalculatorPlugin.getPlugin().getCobInfo(false, "Wizard wear");
if (useCOB && (cobInfo == null || cobInfo.displayCob == null)) {
if (useCOB && (cobInfo == null || cobInfo.displayCob == null)) {
sendError("Unknown COB! BG reading missing or recent app restart?");
return;
}
@ -244,7 +244,8 @@ public class ActionStringHandler {
rMessage += "\nFrom Carbs: " + format.format(bolusWizard.getInsulinFromCarbs()) + "U";
if (useCOB)
rMessage += "\nFrom" + formatInt.format(cobInfo.displayCob) + "g COB : " + format.format(bolusWizard.getInsulinFromCOB()) + "U";
if (useBG) rMessage += "\nFrom BG: " + format.format(bolusWizard.getInsulinFromBG()) + "U";
if (useBG)
rMessage += "\nFrom BG: " + format.format(bolusWizard.getInsulinFromBG()) + "U";
if (useBolusIOB)
rMessage += "\nBolus IOB: " + format.format(bolusWizard.getInsulinFromBolusIOB()) + "U";
if (useBasalIOB)
@ -327,17 +328,17 @@ public class ActionStringHandler {
int carbs = SafeParse.stringToInt(act[1]);
int starttime = SafeParse.stringToInt(act[2]);
int duration = SafeParse.stringToInt(act[3]);
long starttimestamp = System.currentTimeMillis() + starttime*60*1000;
long starttimestamp = System.currentTimeMillis() + starttime * 60 * 1000;
Integer carbsAfterConstraints = MainApp.getConstraintChecker().applyCarbsConstraints(new Constraint<>(carbs)).value();
rMessage += MainApp.gs(R.string.carbs) + ": " + carbsAfterConstraints + "g";
rMessage += "\n" + MainApp.gs(R.string.time) + ": " + DateUtil.timeString(starttimestamp);
rMessage += "\n" + MainApp.gs(R.string.time) + ": " + DateUtil.timeString(starttimestamp);
rMessage += "\n" + MainApp.gs(R.string.duration) + ": " + duration + "h";
if ( (carbsAfterConstraints - carbs != 0)) {
if ((carbsAfterConstraints - carbs != 0)) {
rMessage += "\n" + MainApp.gs(R.string.constraintapllied);
}
if(carbsAfterConstraints <= 0){
if (carbsAfterConstraints <= 0) {
sendError("Carbs = 0! No action taken!");
return;
}
@ -627,14 +628,14 @@ public class ActionStringHandler {
int timeshift = SafeParse.stringToInt(act[1]);
int percentage = SafeParse.stringToInt(act[2]);
setCPP(timeshift, percentage);
} else if ("ecarbs".equals(act[0])) {
} else if ("ecarbs".equals(act[0])) {
int carbs = SafeParse.stringToInt(act[1]);
long starttime = SafeParse.stringToLong(act[2]);
int duration = SafeParse.stringToInt(act[3]);
doECarbs(carbs, starttime, duration);
} else if ("dismissoverviewnotification".equals(act[0])) {
MainApp.bus().post(new EventDismissNotification(SafeParse.stringToInt(act[1])));
RxBus.INSTANCE.send(new EventDismissNotification(SafeParse.stringToInt(act[1])));
} else if ("changeRequest".equals(act[0])) {
LoopPlugin.getPlugin().acceptChangeRequest();
NotificationManager notificationManager =

View file

@ -316,11 +316,11 @@ public class WatchUpdaterService extends WearableListenerService implements Goog
}
if (lowLine < 1) {
lowLine = OverviewPlugin.bgTargetLow;
lowLine = OverviewPlugin.INSTANCE.getBgTargetLow();
}
if (highLine < 1) {
highLine = OverviewPlugin.bgTargetHigh;
highLine = OverviewPlugin.INSTANCE.getBgTargetHigh();
}
long sgvLevel = 0l;

View file

@ -1,19 +1,18 @@
package info.nightscout.androidaps.plugins.insulin;
import com.squareup.otto.Bus;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.Iob;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.treatments.Treatment;
import info.nightscout.androidaps.interfaces.InsulinInterface;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginDescription;
import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification;
import info.nightscout.androidaps.plugins.treatments.Treatment;
/**
* Created by adrian on 13.08.2017.
@ -35,10 +34,6 @@ public abstract class InsulinOrefBasePlugin extends PluginBase implements Insuli
);
}
public Bus getBus() {
return MainApp.bus();
}
@Override
public double getDia() {
double dia = getUserDefinedDia();
@ -54,7 +49,7 @@ public abstract class InsulinOrefBasePlugin extends PluginBase implements Insuli
if ((System.currentTimeMillis() - lastWarned) > 60 * 1000) {
lastWarned = System.currentTimeMillis();
Notification notification = new Notification(Notification.SHORT_DIA, String.format(this.getNotificationPattern(), dia, MIN_DIA), Notification.URGENT);
this.getBus().post(new EventNewNotification(notification));
RxBus.INSTANCE.send(new EventNewNotification(notification));
}
}

View file

@ -3,6 +3,7 @@ package info.nightscout.androidaps.plugins.iob.iobCobCalculator;
import android.content.Context;
import android.os.PowerManager;
import android.os.SystemClock;
import androidx.collection.LongSparseArray;
import org.slf4j.Logger;
@ -24,6 +25,7 @@ import info.nightscout.androidaps.db.TempTarget;
import info.nightscout.androidaps.events.Event;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.aps.openAPSSMB.SMBDefaults;
import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification;
@ -199,7 +201,7 @@ public class IobCobOref1Thread extends Thread {
log.debug(bucketed_data.toString());
log.debug(IobCobCalculatorPlugin.getPlugin().getBgReadings().toString());
Notification notification = new Notification(Notification.SENDLOGFILES, MainApp.gs(R.string.sendlogfiles), Notification.LOW);
MainApp.bus().post(new EventNewNotification(notification));
RxBus.INSTANCE.send(new EventNewNotification(notification));
SP.putBoolean("log_AUTOSENS", true);
break;
}
@ -225,7 +227,7 @@ public class IobCobOref1Thread extends Thread {
log.debug(bucketed_data.toString());
log.debug(IobCobCalculatorPlugin.getPlugin().getBgReadings().toString());
Notification notification = new Notification(Notification.SENDLOGFILES, MainApp.gs(R.string.sendlogfiles), Notification.LOW);
MainApp.bus().post(new EventNewNotification(notification));
RxBus.INSTANCE.send(new EventNewNotification(notification));
SP.putBoolean("log_AUTOSENS", true);
break;
}

View file

@ -199,7 +199,7 @@ public class IobCobThread extends Thread {
log.debug(bucketed_data.toString());
log.debug(IobCobCalculatorPlugin.getPlugin().getBgReadings().toString());
Notification notification = new Notification(Notification.SENDLOGFILES, MainApp.gs(R.string.sendlogfiles), Notification.LOW);
MainApp.bus().post(new EventNewNotification(notification));
RxBus.INSTANCE.send(new EventNewNotification(notification));
SP.putBoolean("log_AUTOSENS", true);
break;
}
@ -225,7 +225,7 @@ public class IobCobThread extends Thread {
log.debug(bucketed_data.toString());
log.debug(IobCobCalculatorPlugin.getPlugin().getBgReadings().toString());
Notification notification = new Notification(Notification.SENDLOGFILES, MainApp.gs(R.string.sendlogfiles), Notification.LOW);
MainApp.bus().post(new EventNewNotification(notification));
RxBus.INSTANCE.send(new EventNewNotification(notification));
SP.putBoolean("log_AUTOSENS", true);
break;
}

View file

@ -38,6 +38,7 @@ import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.interfaces.PumpDescription;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.common.ManufacturerType;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
@ -66,6 +67,7 @@ import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.InstanceId;
import info.nightscout.androidaps.utils.SP;
/**
* Created by mike on 05.08.2016.
*/
@ -231,15 +233,15 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint
// issues a READSTATE when starting to issue commands which initializes the pump
log.error("setNewBasalProfile not initialized");
Notification notification = new Notification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED, MainApp.gs(R.string.pumpNotInitializedProfileNotSet), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(notification));
RxBus.INSTANCE.send(new EventNewNotification(notification));
return new PumpEnactResult().success(false).enacted(false).comment(MainApp.gs(R.string.pumpNotInitializedProfileNotSet));
}
BasalProfile requestedBasalProfile = convertProfileToComboProfile(profile);
if (pump.basalProfile.equals(requestedBasalProfile)) {
//dismiss previously "FAILED" overview notifications
MainApp.bus().post(new EventDismissNotification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED));
MainApp.bus().post(new EventDismissNotification(Notification.FAILED_UDPATE_PROFILE));
RxBus.INSTANCE.send(new EventDismissNotification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED));
RxBus.INSTANCE.send(new EventDismissNotification(Notification.FAILED_UDPATE_PROFILE));
return new PumpEnactResult().success(true).enacted(false);
}
@ -252,18 +254,18 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint
() -> ruffyScripter.setBasalProfile(requestedBasalProfile));
if (!setResult.success) {
Notification notification = new Notification(Notification.FAILED_UDPATE_PROFILE, MainApp.gs(R.string.failedupdatebasalprofile), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(notification));
RxBus.INSTANCE.send(new EventNewNotification(notification));
return new PumpEnactResult().success(false).enacted(false).comment(MainApp.gs(R.string.failedupdatebasalprofile));
}
pump.basalProfile = requestedBasalProfile;
//dismiss previously "FAILED" overview notifications
MainApp.bus().post(new EventDismissNotification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED));
MainApp.bus().post(new EventDismissNotification(Notification.FAILED_UDPATE_PROFILE));
RxBus.INSTANCE.send(new EventDismissNotification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED));
RxBus.INSTANCE.send(new EventDismissNotification(Notification.FAILED_UDPATE_PROFILE));
//issue success notification
Notification notification = new Notification(Notification.PROFILE_SET_OK, MainApp.gs(R.string.profile_set_ok), Notification.INFO, 60);
MainApp.bus().post(new EventNewNotification(notification));
RxBus.INSTANCE.send(new EventNewNotification(notification));
return new PumpEnactResult().success(true).enacted(true);
}
@ -339,7 +341,7 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint
// trigger a connect, which will update state and check history
CommandResult stateResult = runCommand(null, 1, ruffyScripter::readPumpState);
if (stateResult.invalidSetup) {
MainApp.bus().post(new EventNewNotification(
RxBus.INSTANCE.send(new EventNewNotification(
new Notification(Notification.COMBO_PUMP_ALARM, MainApp.gs(R.string.combo_invalid_setup), Notification.URGENT)));
return;
}
@ -360,7 +362,7 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint
MainApp.gs(R.string.combo_force_disabled_notification),
Notification.URGENT);
n.soundId = R.raw.alarm;
MainApp.bus().post(new EventNewNotification(n));
RxBus.INSTANCE.send(new EventNewNotification(n));
return;
}
@ -382,7 +384,7 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint
long now = System.currentTimeMillis();
if (lastBolusTimestamp < now - 24 * 60 * 60 * 1000 || lastBolusTimestamp > now + 5 * 60 * 1000) {
Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, MainApp.gs(R.string.combo_check_date), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(notification));
RxBus.INSTANCE.send(new EventNewNotification(notification));
}
}
@ -600,7 +602,7 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint
long now = System.currentTimeMillis();
if (lastPumpBolus.timestamp < now - 10 * 60 * 1000 || lastPumpBolus.timestamp > now + 10 * 60 * 1000) {
Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, MainApp.gs(R.string.combo_suspious_bolus_time), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(notification));
RxBus.INSTANCE.send(new EventNewNotification(notification));
}
// update `recentBoluses` so the bolus was just delivered won't be detected as a new
@ -627,7 +629,7 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint
} finally {
pump.activity = null;
MainApp.bus().post(new EventComboPumpUpdateGUI());
MainApp.bus().post(new EventRefreshOverview("Bolus"));
RxBus.INSTANCE.send(new EventRefreshOverview("Bolus"));
cancelBolus = false;
}
}
@ -648,7 +650,9 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint
}
}
/** Creates a treatment record based on the request in DetailBolusInfo and the delivered bolus. */
/**
* Creates a treatment record based on the request in DetailBolusInfo and the delivered bolus.
*/
private boolean addBolusToTreatments(DetailedBolusInfo detailedBolusInfo, Bolus lastPumpBolus) {
DetailedBolusInfo dbi = detailedBolusInfo.copy();
dbi.date = calculateFakeBolusDate(lastPumpBolus);
@ -661,7 +665,7 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint
log.error("Adding treatment record failed", e);
if (dbi.isSMB) {
Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, MainApp.gs(R.string.combo_error_updating_treatment_record), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(notification));
RxBus.INSTANCE.send(new EventNewNotification(notification));
}
return false;
}
@ -880,7 +884,7 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint
MainApp.gs(R.string.combo_force_disabled_notification),
Notification.URGENT);
n.soundId = R.raw.alarm;
MainApp.bus().post(new EventNewNotification(n));
RxBus.INSTANCE.send(new EventNewNotification(n));
ConfigBuilderPlugin.getPlugin().getCommandQueue().cancelTempBasal(true, null);
}
updateLocalData(commandResult);
@ -926,7 +930,7 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint
notification.id = Notification.COMBO_PUMP_ALARM;
notification.level = Notification.URGENT;
notification.text = MainApp.gs(R.string.combo_is_in_error_state, activeAlert.errorCode, activeAlert.message);
MainApp.bus().post(new EventNewNotification(notification));
RxBus.INSTANCE.send(new EventNewNotification(notification));
return preCheckResult.success(false);
}
}
@ -989,10 +993,10 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint
if (readBasalResult.success) {
pump.basalProfile = readBasalResult.basalProfile;
Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, MainApp.gs(R.string.combo_warning_pump_basal_rate_changed), Notification.NORMAL);
MainApp.bus().post(new EventNewNotification(notification));
RxBus.INSTANCE.send(new EventNewNotification(notification));
} else {
Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, MainApp.gs(R.string.combo_error_failure_reading_changed_basal_rate), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(notification));
RxBus.INSTANCE.send(new EventNewNotification(notification));
}
}
}
@ -1008,12 +1012,12 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint
if (L.isEnabled(L.PUMP))
log.debug("Pump clock needs update, pump time: " + state.pumpTime + " (" + new Date(state.pumpTime) + ")");
Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, MainApp.gs(R.string.combo_notification_check_time_date), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(notification));
RxBus.INSTANCE.send(new EventNewNotification(notification));
} else if (Math.abs(state.pumpTime - System.currentTimeMillis()) >= 3 * 60 * 1000) {
if (L.isEnabled(L.PUMP))
log.debug("Pump clock needs update, pump time: " + state.pumpTime + " (" + new Date(state.pumpTime) + ")");
Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, MainApp.gs(R.string.combo_notification_check_time_date), Notification.NORMAL);
MainApp.bus().post(new EventNewNotification(notification));
RxBus.INSTANCE.send(new EventNewNotification(notification));
}
}
@ -1035,7 +1039,7 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint
} else if (activeAlert.warningCode == PumpWarningCodes.TBR_CANCELLED) {
notification.text = MainApp.gs(R.string.combo_pump_tbr_cancelled_warrning);
}
MainApp.bus().post(new EventNewNotification(notification));
RxBus.INSTANCE.send(new EventNewNotification(notification));
}
private void checkForUnsafeUsage(CommandResult commandResult) {
@ -1058,7 +1062,7 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint
MainApp.gs(R.string.combo_low_suspend_forced_notification),
Notification.URGENT);
n.soundId = R.raw.alarm;
MainApp.bus().post(new EventNewNotification(n));
RxBus.INSTANCE.send(new EventNewNotification(n));
violationWarningRaisedForBolusAt = lowSuspendOnlyLoopEnforcedUntil;
ConfigBuilderPlugin.getPlugin().getCommandQueue().cancelTempBasal(true, null);
}
@ -1132,7 +1136,9 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint
return historyResult.success;
}
/** Return value indicates whether a new record was created. */
/**
* Return value indicates whether a new record was created.
*/
private boolean updateDbFromPumpHistory(@NonNull PumpHistory history) {
boolean updated = false;
for (Bolus pumpBolus : history.bolusHistory) {
@ -1216,7 +1222,7 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint
log.debug("Bolus with same amount within the same minute imported. Only one will make it to the DB.");
Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, MainApp.gs(R.string.
combo_error_multiple_boluses_with_identical_timestamp), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(notification));
RxBus.INSTANCE.send(new EventNewNotification(notification));
}
pumpHistoryChanged = updateDbFromPumpHistory(historyResult.history);

View file

@ -29,6 +29,7 @@ import info.nightscout.androidaps.interfaces.ProfileInterface;
import info.nightscout.androidaps.interfaces.PumpDescription;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.common.ManufacturerType;
import info.nightscout.androidaps.plugins.general.actions.defs.CustomAction;
import info.nightscout.androidaps.plugins.general.actions.defs.CustomActionType;
@ -107,22 +108,22 @@ public abstract class AbstractDanaRPlugin extends PluginBase implements PumpInte
if (!isInitialized()) {
log.error("setNewBasalProfile not initialized");
Notification notification = new Notification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED, MainApp.gs(R.string.pumpNotInitializedProfileNotSet), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(notification));
RxBus.INSTANCE.send(new EventNewNotification(notification));
result.comment = MainApp.gs(R.string.pumpNotInitializedProfileNotSet);
return result;
} else {
MainApp.bus().post(new EventDismissNotification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED));
RxBus.INSTANCE.send(new EventDismissNotification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED));
}
if (!sExecutionService.updateBasalsInPump(profile)) {
Notification notification = new Notification(Notification.FAILED_UDPATE_PROFILE, MainApp.gs(R.string.failedupdatebasalprofile), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(notification));
RxBus.INSTANCE.send(new EventNewNotification(notification));
result.comment = MainApp.gs(R.string.failedupdatebasalprofile);
return result;
} else {
MainApp.bus().post(new EventDismissNotification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED));
MainApp.bus().post(new EventDismissNotification(Notification.FAILED_UDPATE_PROFILE));
RxBus.INSTANCE.send(new EventDismissNotification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED));
RxBus.INSTANCE.send(new EventDismissNotification(Notification.FAILED_UDPATE_PROFILE));
Notification notification = new Notification(Notification.PROFILE_SET_OK, MainApp.gs(R.string.profile_set_ok), Notification.INFO, 60);
MainApp.bus().post(new EventNewNotification(notification));
RxBus.INSTANCE.send(new EventNewNotification(notification));
result.success = true;
result.enacted = true;
result.comment = "OK";

View file

@ -6,6 +6,7 @@ import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification;
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification;
@ -45,9 +46,9 @@ public class MsgInitConnStatusBolus extends MessageBase {
if (!pump.isExtendedBolusEnabled) {
Notification notification = new Notification(Notification.EXTENDED_BOLUS_DISABLED, MainApp.gs(R.string.danar_enableextendedbolus), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(notification));
RxBus.INSTANCE.send(new EventNewNotification(notification));
} else {
MainApp.bus().post(new EventDismissNotification(Notification.EXTENDED_BOLUS_DISABLED));
RxBus.INSTANCE.send(new EventDismissNotification(Notification.EXTENDED_BOLUS_DISABLED));
}
}
}

View file

@ -6,6 +6,7 @@ import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification;
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification;
@ -45,13 +46,13 @@ public class MsgInitConnStatusOption extends MessageBase {
if (!DanaRPump.getInstance().isPasswordOK()) {
Notification notification = new Notification(Notification.WRONG_PUMP_PASSWORD, MainApp.gs(R.string.wrongpumppassword), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(notification));
RxBus.INSTANCE.send(new EventNewNotification(notification));
} else {
MainApp.bus().post(new EventDismissNotification(Notification.WRONG_PUMP_PASSWORD));
RxBus.INSTANCE.send(new EventDismissNotification(Notification.WRONG_PUMP_PASSWORD));
}
// This is last message of initial sequence
if (ConfigBuilderPlugin.getPlugin().getActivePump() != null )
if (ConfigBuilderPlugin.getPlugin().getActivePump() != null)
ConfigBuilderPlugin.getPlugin().getActivePump().finishHandshaking();
}

View file

@ -8,6 +8,7 @@ import info.nightscout.androidaps.R;
import info.nightscout.androidaps.events.EventRefreshGui;
import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification;
@ -29,7 +30,7 @@ public class MsgInitConnStatusTime extends MessageBase {
public void handleMessage(byte[] bytes) {
if (bytes.length - 10 > 7) {
Notification notification = new Notification(Notification.WRONG_DRIVER, MainApp.gs(R.string.pumpdrivercorrected), Notification.NORMAL);
MainApp.bus().post(new EventNewNotification(notification));
RxBus.INSTANCE.send(new EventNewNotification(notification));
MainApp.getSpecificPlugin(DanaRPlugin.class).disconnect("Wrong Model");
log.error("Wrong model selected. Switching to Korean DanaR");
MainApp.getSpecificPlugin(DanaRKoreanPlugin.class).setPluginEnabled(PluginType.PUMP, true);

View file

@ -6,6 +6,7 @@ import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification;
@ -37,12 +38,12 @@ public class MsgSetBasalProfile extends MessageBase {
if (L.isEnabled(L.PUMPCOMM))
log.debug("Set basal profile result: " + result + " FAILED!!!");
Notification reportFail = new Notification(Notification.PROFILE_SET_FAILED, MainApp.gs(R.string.profile_set_failed), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(reportFail));
RxBus.INSTANCE.send(new EventNewNotification(reportFail));
} else {
if (L.isEnabled(L.PUMPCOMM))
log.debug("Set basal profile result: " + result);
Notification reportOK = new Notification(Notification.PROFILE_SET_OK, MainApp.gs(R.string.profile_set_ok), Notification.INFO, 60);
MainApp.bus().post(new EventNewNotification(reportOK));
RxBus.INSTANCE.send(new EventNewNotification(reportOK));
}
}

View file

@ -6,6 +6,7 @@ import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification;
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification;
@ -34,12 +35,12 @@ public class MsgSetSingleBasalProfile extends MessageBase {
if (L.isEnabled(L.PUMPCOMM))
log.debug("Set basal profile result: " + result + " FAILED!!!");
Notification reportFail = new Notification(Notification.PROFILE_SET_FAILED, MainApp.gs(R.string.profile_set_failed), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(reportFail));
RxBus.INSTANCE.send(new EventNewNotification(reportFail));
} else {
if (L.isEnabled(L.PUMPCOMM))
log.debug("Set basal profile result: " + result);
Notification reportOK = new Notification(Notification.PROFILE_SET_OK, MainApp.gs(R.string.profile_set_ok), Notification.INFO, 60);
MainApp.bus().post(new EventNewNotification(reportOK));
RxBus.INSTANCE.send(new EventNewNotification(reportOK));
}
}

View file

@ -7,6 +7,7 @@ import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification;
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification;
@ -51,16 +52,16 @@ public class MsgSettingMeal extends MessageBase {
if (pump.basalStep != 0.01d) {
Notification notification = new Notification(Notification.WRONGBASALSTEP, MainApp.gs(R.string.danar_setbasalstep001), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(notification));
RxBus.INSTANCE.send(new EventNewNotification(notification));
} else {
MainApp.bus().post(new EventDismissNotification(Notification.WRONGBASALSTEP));
RxBus.INSTANCE.send(new EventDismissNotification(Notification.WRONGBASALSTEP));
}
if (pump.isConfigUD) {
Notification notification = new Notification(Notification.UD_MODE_ENABLED, MainApp.gs(R.string.danar_switchtouhmode), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(notification));
RxBus.INSTANCE.send(new EventNewNotification(notification));
} else {
MainApp.bus().post(new EventDismissNotification(Notification.UD_MODE_ENABLED));
RxBus.INSTANCE.send(new EventDismissNotification(Notification.UD_MODE_ENABLED));
}
}

View file

@ -217,7 +217,7 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService {
log.debug("Approaching daily limit: " + danaRPump.dailyTotalUnits + "/" + danaRPump.maxDailyTotalUnits);
if (System.currentTimeMillis() > lastApproachingDailyLimit + 30 * 60 * 1000) {
Notification reportFail = new Notification(Notification.APPROACHING_DAILY_LIMIT, MainApp.gs(R.string.approachingdailylimit), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(reportFail));
RxBus.INSTANCE.send(new EventNewNotification(reportFail));
NSUpload.uploadError(MainApp.gs(R.string.approachingdailylimit) + ": " + danaRPump.dailyTotalUnits + "/" + danaRPump.maxDailyTotalUnits + "U");
lastApproachingDailyLimit = System.currentTimeMillis();
}

View file

@ -6,6 +6,7 @@ import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification;
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification;
@ -42,16 +43,16 @@ public class MsgInitConnStatusBasic_k extends MessageBase {
if (pump.isEasyModeEnabled) {
Notification notification = new Notification(Notification.EASYMODE_ENABLED, MainApp.gs(R.string.danar_disableeasymode), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(notification));
RxBus.INSTANCE.send(new EventNewNotification(notification));
} else {
MainApp.bus().post(new EventDismissNotification(Notification.EASYMODE_ENABLED));
RxBus.INSTANCE.send(new EventDismissNotification(Notification.EASYMODE_ENABLED));
}
if (!DanaRPump.getInstance().isPasswordOK()) {
Notification notification = new Notification(Notification.WRONG_PUMP_PASSWORD, MainApp.gs(R.string.wrongpumppassword), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(notification));
RxBus.INSTANCE.send(new EventNewNotification(notification));
} else {
MainApp.bus().post(new EventDismissNotification(Notification.WRONG_PUMP_PASSWORD));
RxBus.INSTANCE.send(new EventDismissNotification(Notification.WRONG_PUMP_PASSWORD));
}
}
}

View file

@ -6,6 +6,7 @@ import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification;
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification;
@ -48,9 +49,9 @@ public class MsgInitConnStatusBolus_k extends MessageBase {
if (!pump.isExtendedBolusEnabled) {
Notification notification = new Notification(Notification.EXTENDED_BOLUS_DISABLED, MainApp.gs(R.string.danar_enableextendedbolus), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(notification));
RxBus.INSTANCE.send(new EventNewNotification(notification));
} else {
MainApp.bus().post(new EventDismissNotification(Notification.EXTENDED_BOLUS_DISABLED));
RxBus.INSTANCE.send(new EventDismissNotification(Notification.EXTENDED_BOLUS_DISABLED));
}
// This is last message of initial sequence

View file

@ -8,6 +8,7 @@ import info.nightscout.androidaps.R;
import info.nightscout.androidaps.events.EventRefreshGui;
import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification;
@ -31,7 +32,7 @@ public class MsgInitConnStatusTime_k extends MessageBase {
if (bytes.length - 10 < 10) {
Notification notification = new Notification(Notification.WRONG_DRIVER, MainApp.gs(R.string.pumpdrivercorrected), Notification.NORMAL);
MainApp.bus().post(new EventNewNotification(notification));
RxBus.INSTANCE.send(new EventNewNotification(notification));
DanaRKoreanPlugin.getPlugin().disconnect("Wrong Model");
log.error("Wrong model selected. Switching to export DanaR");
MainApp.getSpecificPlugin(DanaRKoreanPlugin.class).setPluginEnabled(PluginType.PUMP, false);

View file

@ -220,7 +220,7 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService {
log.debug("Approaching daily limit: " + danaRPump.dailyTotalUnits + "/" + danaRPump.maxDailyTotalUnits);
if (System.currentTimeMillis() > lastApproachingDailyLimit + 30 * 60 * 1000) {
Notification reportFail = new Notification(Notification.APPROACHING_DAILY_LIMIT, MainApp.gs(R.string.approachingdailylimit), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(reportFail));
RxBus.INSTANCE.send(new EventNewNotification(reportFail));
NSUpload.uploadError(MainApp.gs(R.string.approachingdailylimit) + ": " + danaRPump.dailyTotalUnits + "/" + danaRPump.maxDailyTotalUnits + "U");
lastApproachingDailyLimit = System.currentTimeMillis();
}

View file

@ -38,6 +38,7 @@ import info.nightscout.androidaps.interfaces.ProfileInterface;
import info.nightscout.androidaps.interfaces.PumpDescription;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.common.ManufacturerType;
import info.nightscout.androidaps.plugins.configBuilder.DetailedBolusInfoStorage;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
@ -305,22 +306,22 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte
if (!isInitialized()) {
log.error("setNewBasalProfile not initialized");
Notification notification = new Notification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED, MainApp.gs(R.string.pumpNotInitializedProfileNotSet), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(notification));
RxBus.INSTANCE.send(new EventNewNotification(notification));
result.comment = MainApp.gs(R.string.pumpNotInitializedProfileNotSet);
return result;
} else {
MainApp.bus().post(new EventDismissNotification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED));
RxBus.INSTANCE.send(new EventDismissNotification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED));
}
if (!danaRSService.updateBasalsInPump(profile)) {
Notification notification = new Notification(Notification.FAILED_UDPATE_PROFILE, MainApp.gs(R.string.failedupdatebasalprofile), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(notification));
RxBus.INSTANCE.send(new EventNewNotification(notification));
result.comment = MainApp.gs(R.string.failedupdatebasalprofile);
return result;
} else {
MainApp.bus().post(new EventDismissNotification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED));
MainApp.bus().post(new EventDismissNotification(Notification.FAILED_UDPATE_PROFILE));
RxBus.INSTANCE.send(new EventDismissNotification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED));
RxBus.INSTANCE.send(new EventDismissNotification(Notification.FAILED_UDPATE_PROFILE));
Notification notification = new Notification(Notification.PROFILE_SET_OK, MainApp.gs(R.string.profile_set_ok), Notification.INFO, 60);
MainApp.bus().post(new EventNewNotification(notification));
RxBus.INSTANCE.send(new EventNewNotification(notification));
result.success = true;
result.enacted = true;
result.comment = "OK";
@ -361,10 +362,14 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte
}
@Override
public double getReservoirLevel() { return DanaRPump.getInstance().reservoirRemainingUnits; }
public double getReservoirLevel() {
return DanaRPump.getInstance().reservoirRemainingUnits;
}
@Override
public int getBatteryLevel() { return DanaRPump.getInstance().batteryRemaining; }
public int getBatteryLevel() {
return DanaRPump.getInstance().batteryRemaining;
}
@Override
public synchronized PumpEnactResult deliverTreatment(DetailedBolusInfo detailedBolusInfo) {

View file

@ -11,6 +11,7 @@ import java.util.Locale;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification;
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification;
@ -57,9 +58,9 @@ public class DanaRS_Packet_Basal_Get_Basal_Rate extends DanaRS_Packet {
if (pump.basalStep != 0.01d) {
failed = true;
Notification notification = new Notification(Notification.WRONGBASALSTEP, MainApp.gs(R.string.danar_setbasalstep001), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(notification));
RxBus.INSTANCE.send(new EventNewNotification(notification));
} else {
MainApp.bus().post(new EventDismissNotification(Notification.WRONGBASALSTEP));
RxBus.INSTANCE.send(new EventDismissNotification(Notification.WRONGBASALSTEP));
}
}

View file

@ -8,6 +8,7 @@ import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification;
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification;
@ -105,10 +106,10 @@ public class DanaRS_Packet_Bolus_Get_Bolus_Option extends DanaRS_Packet {
if (!pump.isExtendedBolusEnabled) {
Notification notification = new Notification(Notification.EXTENDED_BOLUS_DISABLED, MainApp.gs(R.string.danar_enableextendedbolus), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(notification));
RxBus.INSTANCE.send(new EventNewNotification(notification));
failed = true;
} else {
MainApp.bus().post(new EventDismissNotification(Notification.EXTENDED_BOLUS_DISABLED));
RxBus.INSTANCE.send(new EventDismissNotification(Notification.EXTENDED_BOLUS_DISABLED));
}
if (L.isEnabled(L.PUMPCOMM)) {

View file

@ -8,6 +8,7 @@ import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification;
import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump;
@ -24,7 +25,7 @@ public class DanaRS_Packet_General_Get_Pump_Check extends DanaRS_Packet {
@Override
public void handleMessage(byte[] data) {
if (data.length <5){
if (data.length < 5) {
failed = true;
return;
}
@ -49,7 +50,7 @@ public class DanaRS_Packet_General_Get_Pump_Check extends DanaRS_Packet {
}
if (pump.productCode < 2) {
MainApp.bus().post(new EventNewNotification(new Notification(Notification.UNSUPPORTED_FIRMWARE, MainApp.gs(R.string.unsupportedfirmware), Notification.URGENT)));
RxBus.INSTANCE.send(new EventNewNotification(new Notification(Notification.UNSUPPORTED_FIRMWARE, MainApp.gs(R.string.unsupportedfirmware), Notification.URGENT)));
}
}

View file

@ -26,6 +26,8 @@ import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.events.EventPumpStatusChanged;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload;
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification;
import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump;
@ -35,7 +37,6 @@ import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRSMessageHashTabl
import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet;
import info.nightscout.androidaps.plugins.pump.danaRS.events.EventDanaRSPacket;
import info.nightscout.androidaps.plugins.pump.danaRS.events.EventDanaRSPairingSuccess;
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload;
import info.nightscout.androidaps.utils.SP;
/**
@ -454,7 +455,7 @@ public class BLEComm {
MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTED, MainApp.gs(R.string.pumperror)));
NSUpload.uploadError(MainApp.gs(R.string.pumperror));
Notification n = new Notification(Notification.PUMPERROR, MainApp.gs(R.string.pumperror), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(n));
RxBus.INSTANCE.send(new EventNewNotification(n));
} else if (inputBuffer.length == 6 && inputBuffer[2] == 'B' && inputBuffer[3] == 'U' && inputBuffer[4] == 'S' && inputBuffer[5] == 'Y') {
if (L.isEnabled(L.PUMPBTCOMM))
log.debug("<<<<< " + "ENCRYPTION__PUMP_CHECK (BUSY)" + " " + DanaRS_Packet.toHexString(inputBuffer));
@ -468,7 +469,7 @@ public class BLEComm {
MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTED, MainApp.gs(R.string.connectionerror)));
SP.remove(MainApp.gs(R.string.key_danars_pairingkey) + DanaRSPlugin.mDeviceName);
Notification n = new Notification(Notification.WRONGSERIALNUMBER, MainApp.gs(R.string.wrongpassword), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(n));
RxBus.INSTANCE.send(new EventNewNotification(n));
}
break;
// 2nd packet, pairing key
@ -664,9 +665,9 @@ public class BLEComm {
private void SendPumpCheck() {
// 1st message sent to pump after connect
String devicename = getConnectDeviceName();
if(devicename == null || devicename.equals("")){
if (devicename == null || devicename.equals("")) {
Notification n = new Notification(Notification.DEVICENOTPAIRED, MainApp.gs(R.string.pairfirst), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(n));
RxBus.INSTANCE.send(new EventNewNotification(n));
return;
}
byte[] bytes = BleCommandUtil.getInstance().getEncryptedPacket(BleCommandUtil.DANAR_PACKET__OPCODE_ENCRYPTION__PUMP_CHECK, null, devicename);

View file

@ -220,7 +220,7 @@ public class DanaRSService extends Service {
log.debug("Approaching daily limit: " + danaRPump.dailyTotalUnits + "/" + danaRPump.maxDailyTotalUnits);
if (System.currentTimeMillis() > lastApproachingDailyLimit + 30 * 60 * 1000) {
Notification reportFail = new Notification(Notification.APPROACHING_DAILY_LIMIT, MainApp.gs(R.string.approachingdailylimit), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(reportFail));
RxBus.INSTANCE.send(new EventNewNotification(reportFail));
NSUpload.uploadError(MainApp.gs(R.string.approachingdailylimit) + ": " + danaRPump.dailyTotalUnits + "/" + danaRPump.maxDailyTotalUnits + "U");
lastApproachingDailyLimit = System.currentTimeMillis();
}

View file

@ -8,6 +8,7 @@ import info.nightscout.androidaps.R;
import info.nightscout.androidaps.events.EventRefreshGui;
import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification;
@ -43,7 +44,7 @@ public class MsgCheckValue_v2 extends MessageBase {
if (pump.model != DanaRPump.EXPORT_MODEL) {
pump.lastConnection = 0;
Notification notification = new Notification(Notification.WRONG_DRIVER, MainApp.gs(R.string.pumpdrivercorrected), Notification.NORMAL);
MainApp.bus().post(new EventNewNotification(notification));
RxBus.INSTANCE.send(new EventNewNotification(notification));
MainApp.getSpecificPlugin(DanaRPlugin.class).disconnect("Wrong Model");
log.error("Wrong model selected. Switching to Korean DanaR");
MainApp.getSpecificPlugin(DanaRKoreanPlugin.class).setPluginEnabled(PluginType.PUMP, true);
@ -68,7 +69,7 @@ public class MsgCheckValue_v2 extends MessageBase {
if (pump.protocol != 2) {
pump.lastConnection = 0;
Notification notification = new Notification(Notification.WRONG_DRIVER, MainApp.gs(R.string.pumpdrivercorrected), Notification.NORMAL);
MainApp.bus().post(new EventNewNotification(notification));
RxBus.INSTANCE.send(new EventNewNotification(notification));
DanaRKoreanPlugin.getPlugin().disconnect("Wrong Model");
log.error("Wrong model selected. Switching to non APS DanaR");
(MainApp.getSpecificPlugin(DanaRv2Plugin.class)).setPluginEnabled(PluginType.PUMP, false);

View file

@ -263,7 +263,7 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService {
log.debug("Approaching daily limit: " + danaRPump.dailyTotalUnits + "/" + danaRPump.maxDailyTotalUnits);
if (System.currentTimeMillis() > lastApproachingDailyLimit + 30 * 60 * 1000) {
Notification reportFail = new Notification(Notification.APPROACHING_DAILY_LIMIT, MainApp.gs(R.string.approachingdailylimit), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(reportFail));
RxBus.INSTANCE.send(new EventNewNotification(reportFail));
NSUpload.uploadError(MainApp.gs(R.string.approachingdailylimit) + ": " + danaRPump.dailyTotalUnits + "/" + danaRPump.maxDailyTotalUnits + "U");
lastApproachingDailyLimit = System.currentTimeMillis();
}

View file

@ -43,6 +43,7 @@ import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.interfaces.PumpDescription;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.common.ManufacturerType;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
@ -354,7 +355,7 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con
setDateTimeMessage.setPumpTime(pumpTime);
connectionService.requestMessage(setDateTimeMessage).await();
Notification notification = new Notification(Notification.INSIGHT_DATE_TIME_UPDATED, MainApp.gs(R.string.pump_time_updated), Notification.INFO, 60);
MainApp.bus().post(new EventNewNotification(notification));
RxBus.INSTANCE.send(new EventNewNotification(notification));
}
}
@ -440,7 +441,7 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con
@Override
public PumpEnactResult setNewBasalProfile(Profile profile) {
PumpEnactResult result = new PumpEnactResult();
MainApp.bus().post(new EventDismissNotification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED));
RxBus.INSTANCE.send(new EventDismissNotification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED));
List<BasalProfileBlock> profileBlocks = new ArrayList<>();
for (int i = 0; i < profile.getBasalValues().length; i++) {
Profile.ProfileValue basalValue = profile.getBasalValues()[i];
@ -460,9 +461,9 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con
BRProfileBlock profileBlock = new BRProfile1Block();
profileBlock.setProfileBlocks(profileBlocks);
ParameterBlockUtil.writeConfigurationBlock(connectionService, profileBlock);
MainApp.bus().post(new EventDismissNotification(Notification.FAILED_UDPATE_PROFILE));
RxBus.INSTANCE.send(new EventDismissNotification(Notification.FAILED_UDPATE_PROFILE));
Notification notification = new Notification(Notification.PROFILE_SET_OK, MainApp.gs(R.string.profile_set_ok), Notification.INFO, 60);
MainApp.bus().post(new EventNewNotification(notification));
RxBus.INSTANCE.send(new EventNewNotification(notification));
result.success = true;
result.enacted = true;
result.comment = MainApp.gs(R.string.virtualpump_resultok);
@ -474,17 +475,17 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con
} catch (AppLayerErrorException e) {
log.info("Exception while setting profile: " + e.getClass().getCanonicalName() + " (" + e.getErrorCode() + ")");
Notification notification = new Notification(Notification.FAILED_UDPATE_PROFILE, MainApp.gs(R.string.failedupdatebasalprofile), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(notification));
RxBus.INSTANCE.send(new EventNewNotification(notification));
result.comment = ExceptionTranslator.getString(e);
} catch (InsightException e) {
log.info("Exception while setting profile: " + e.getClass().getCanonicalName());
Notification notification = new Notification(Notification.FAILED_UDPATE_PROFILE, MainApp.gs(R.string.failedupdatebasalprofile), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(notification));
RxBus.INSTANCE.send(new EventNewNotification(notification));
result.comment = ExceptionTranslator.getString(e);
} catch (Exception e) {
log.error("Exception while setting profile", e);
Notification notification = new Notification(Notification.FAILED_UDPATE_PROFILE, MainApp.gs(R.string.failedupdatebasalprofile), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(notification));
RxBus.INSTANCE.send(new EventNewNotification(notification));
result.comment = ExceptionTranslator.getString(e);
}
return result;
@ -982,7 +983,7 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con
@Override
public String serialNumber() {
if (connectionService == null || alertService == null) return "Unknown";
return connectionService.getPumpSystemIdentification().getSerialNumber();
return connectionService.getPumpSystemIdentification().getSerialNumber();
}
public PumpEnactResult stopPump() {
@ -1585,7 +1586,7 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con
public void onStateChanged(InsightState state) {
if (state == InsightState.CONNECTED) {
statusLoaded = false;
new Handler(Looper.getMainLooper()).post(() -> MainApp.bus().post(new EventDismissNotification(Notification.INSIGHT_TIMEOUT_DURING_HANDSHAKE)));
new Handler(Looper.getMainLooper()).post(() -> RxBus.INSTANCE.send(new EventDismissNotification(Notification.INSIGHT_TIMEOUT_DURING_HANDSHAKE)));
} else if (state == InsightState.NOT_PAIRED) {
connectionService.withdrawConnectionRequest(this);
statusLoaded = false;
@ -1611,7 +1612,7 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con
@Override
public void onTimeoutDuringHandshake() {
Notification notification = new Notification(Notification.INSIGHT_TIMEOUT_DURING_HANDSHAKE, MainApp.gs(R.string.timeout_during_handshake), Notification.URGENT);
new Handler(Looper.getMainLooper()).post(() -> MainApp.bus().post(new EventNewNotification(notification)));
new Handler(Looper.getMainLooper()).post(() -> RxBus.INSTANCE.send(new EventNewNotification(notification)));
}
@Override

View file

@ -765,7 +765,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
if (clock.timeDifference == 0) {
Notification notification = new Notification(Notification.INSIGHT_DATE_TIME_UPDATED, MainApp.gs(R.string.pump_time_updated), Notification.INFO, 60);
MainApp.bus().post(new EventNewNotification(notification));
RxBus.INSTANCE.send(new EventNewNotification(notification));
}
} else {
if ((clock.localDeviceTime.getYear() > 2015)) {

View file

@ -702,7 +702,6 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
// create message
PumpMessage msg;
// if (bodyData == null)
msg = makePumpMessage(commandType);
// send and wait for response
@ -717,8 +716,6 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
byte[] data = null;
int runs = 1;
if (check == null) {
data = response.getRawContentOfFrame();
@ -727,24 +724,21 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
while (checkIfWeHaveMoreData(commandType, response, data)) {
runs++;
PumpMessage response2 = sendAndListen(ackMsg, DEFAULT_TIMEOUT + (DEFAULT_TIMEOUT * retries));
response = sendAndListen(ackMsg, DEFAULT_TIMEOUT + (DEFAULT_TIMEOUT * retries));
// LOG.debug("{} Response: {}", runs, HexDump.toHexStringDisplayable(response2.getRawContent()));
// LOG.debug("{} Response: {}", runs,
// HexDump.toHexStringDisplayable(response2.getMessageBody().getTxData()));
String check2 = checkResponseContent(response2, commandType.commandDescription, 1);
String check2 = checkResponseContent(response, commandType.commandDescription, 1);
if (check2 == null) {
data = ByteUtil.concat(data, response2.getRawContentOfFrame());
data = ByteUtil.concat(data, response.getRawContentOfFrame());
} else {
this.errorMessage = check2;
if (isLogEnabled())
LOG.debug("Error message: " + check2);
LOG.error("Error with response got GetProfile: " + check2);
}
}
@ -783,12 +777,11 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
if (commandType == MedtronicCommandType.GetBasalProfileSTD || //
commandType == MedtronicCommandType.GetBasalProfileA || //
commandType == MedtronicCommandType.GetBasalProfileB) {
byte[] responseRaw = response.getRawContent();
byte[] responseRaw = response.getRawContentOfFrame();
int last = responseRaw.length - 1;
if (isLogEnabled())
LOG.debug("Length: " + data.length);
LOG.debug("Length: " + data.length);
if (data.length >= BasalProfile.MAX_RAW_DATA_SIZE) {
return false;
@ -953,7 +946,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
LOG.warn("Error getting response from RileyLink (error={}, retry={})", e.getMessage(), retries + 1);
}
if (responseMessage!=null)
if (responseMessage != null)
LOG.warn("Set Basal Profile: Invalid response: commandType={},rawData={}", responseMessage.commandType, ByteUtil.shortHexString(responseMessage.getRawContent()));
else
LOG.warn("Set Basal Profile: Null response.");

View file

@ -22,6 +22,8 @@ public class PumpMessage implements RLMessage {
public MessageBody messageBody = new MessageBody();
public String error = null;
public static final int FRAME_DATA_LENGTH = 64;
public PumpMessage(String error) {
this.error = error;
@ -129,9 +131,10 @@ public class PumpMessage implements RLMessage {
return arrayOut;
}
public byte[] getRawContentOfFrame() {
byte[] raw = getRawContent();
return ByteUtil.substring(raw, 0, raw.length - 1);
byte[] raw = messageBody.getTxData();
return ByteUtil.substring(raw, 1, Math.min(FRAME_DATA_LENGTH, raw.length - 1));
}

View file

@ -105,9 +105,9 @@ public enum MedtronicDeviceType {
}
public static boolean isLargerFormat(MedtronicDeviceType model) {
return isSameDevice(model, Medtronic_523andHigher);
}
// public static boolean isLargerFormat(MedtronicDeviceType model) {
// return isSameDevice(model, Medtronic_523andHigher);
// }
public boolean isFamily() {
@ -120,13 +120,17 @@ public enum MedtronicDeviceType {
}
public boolean isLargerFormat() {
// public boolean isLargerFormat() {
// return isSameDevice(this, Medtronic_523andHigher);
// }
public boolean isMedtronic_523orHigher() {
return isSameDevice(this, Medtronic_523andHigher);
}
public int getBolusStrokes() {
return (isLargerFormat(this)) ? 40 : 10;
return (isMedtronic_523orHigher()) ? 40 : 10;
}

View file

@ -231,7 +231,7 @@ public class MedtronicUtil extends RileyLinkUtil {
notificationType.getNotificationType(), //
MainApp.gs(notificationType.getResourceId()), //
notificationType.getNotificationUrgency());
MainApp.bus().post(new EventNewNotification(notification));
RxBus.INSTANCE.send(new EventNewNotification(notification));
}
@ -240,12 +240,12 @@ public class MedtronicUtil extends RileyLinkUtil {
notificationType.getNotificationType(), //
MainApp.gs(notificationType.getResourceId(), parameters), //
notificationType.getNotificationUrgency());
MainApp.bus().post(new EventNewNotification(notification));
RxBus.INSTANCE.send(new EventNewNotification(notification));
}
public static void dismissNotification(MedtronicNotificationType notificationType) {
MainApp.bus().post(new EventDismissNotification(notificationType.getNotificationType()));
RxBus.INSTANCE.send(new EventDismissNotification(notificationType.getNotificationType()));
}

View file

@ -28,6 +28,7 @@ import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.interfaces.PumpDescription;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.common.ManufacturerType;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.general.actions.defs.CustomAction;
@ -219,7 +220,7 @@ public class VirtualPumpPlugin extends PluginBase implements PumpInterface {
PumpEnactResult result = new PumpEnactResult();
result.success = true;
Notification notification = new Notification(Notification.PROFILE_SET_OK, MainApp.gs(R.string.profile_set_ok), Notification.INFO, 60);
MainApp.bus().post(new EventNewNotification(notification));
RxBus.INSTANCE.send(new EventNewNotification(notification));
return result;
}
@ -244,10 +245,14 @@ public class VirtualPumpPlugin extends PluginBase implements PumpInterface {
@Override
public double getReservoirLevel() { return reservoirInUnits; }
public double getReservoirLevel() {
return reservoirInUnits;
}
@Override
public int getBatteryLevel() { return batteryPercent; }
public int getBatteryLevel() {
return batteryPercent;
}
@Override
public PumpEnactResult deliverTreatment(DetailedBolusInfo detailedBolusInfo) {

View file

@ -156,7 +156,7 @@ public class SensitivityOref1Plugin extends AbstractSensitivityPlugin {
log.debug("Records: " + index + " " + pastSensitivity);
Arrays.sort(deviations);
/* Not used in calculation
for (double i = 0.9; i > 0.1; i = i - 0.01) {
if (IobCobCalculatorPlugin.percentile(deviations, (i + 0.01)) >= 0 && IobCobCalculatorPlugin.percentile(deviations, i) < 0) {
if (L.isEnabled(L.AUTOSENS))
@ -164,9 +164,10 @@ public class SensitivityOref1Plugin extends AbstractSensitivityPlugin {
}
if (IobCobCalculatorPlugin.percentile(deviations, (i + 0.01)) > 0 && IobCobCalculatorPlugin.percentile(deviations, i) <= 0) {
if (L.isEnabled(L.AUTOSENS))
log.debug(Math.round(100 * i) + "% of non-meal deviations negative (>50% = resistance)");
log.debug(Math.round(100 * i) + "% of non-meal deviations positive (>50% = resistance)");
}
}
*/
double pSensitive = IobCobCalculatorPlugin.percentile(deviations, 0.50);
double pResistant = IobCobCalculatorPlugin.percentile(deviations, 0.50);

View file

@ -224,7 +224,7 @@ public class Treatment implements DataPointWithLabelInterface, DbObjectBase {
@Override
public double getY() {
return isSMB ? OverviewPlugin.getPlugin().determineLowLine() : yValue;
return isSMB ? OverviewPlugin.INSTANCE.determineLowLine() : yValue;
}
@Override

View file

@ -42,6 +42,7 @@ import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.interfaces.TreatmentsInterface;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload;
@ -725,6 +726,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
}
@Override
@Nullable
public ProfileSwitch getProfileSwitchFromHistory(long time) {
synchronized (profiles) {
return (ProfileSwitch) profiles.getValueToTime(time);
@ -741,7 +743,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
@Override
public void addToHistoryProfileSwitch(ProfileSwitch profileSwitch) {
//log.debug("Adding new TemporaryBasal record" + profileSwitch.log());
MainApp.bus().post(new EventDismissNotification(Notification.PROFILE_SWITCH_MISSING));
RxBus.INSTANCE.send(new EventDismissNotification(Notification.PROFILE_SWITCH_MISSING));
MainApp.getDbHelper().createOrUpdate(profileSwitch);
NSUpload.uploadProfileSwitch(profileSwitch);
}

View file

@ -3,10 +3,11 @@ package info.nightscout.androidaps.queue;
import android.content.Context;
import android.content.Intent;
import android.os.SystemClock;
import androidx.appcompat.app.AppCompatActivity;
import android.text.Html;
import android.text.Spanned;
import androidx.appcompat.app.AppCompatActivity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -21,6 +22,7 @@ import info.nightscout.androidaps.events.EventBolusRequested;
import info.nightscout.androidaps.interfaces.Constraint;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.general.overview.dialogs.BolusProgressDialog;
@ -380,7 +382,7 @@ public class CommandQueue {
if (!MainApp.isEngineeringModeOrRelease()) {
Notification notification = new Notification(Notification.NOT_ENG_MODE_OR_RELEASE, MainApp.gs(R.string.not_eng_mode_or_release), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(notification));
RxBus.INSTANCE.send(new EventNewNotification(notification));
if (callback != null)
callback.result(new PumpEnactResult().success(false).enacted(false).comment(MainApp.gs(R.string.not_eng_mode_or_release))).run();
return false;
@ -393,14 +395,14 @@ public class CommandQueue {
for (Profile.ProfileValue basalValue : basalValues) {
if (basalValue.value < pump.getPumpDescription().basalMinimumRate) {
Notification notification = new Notification(Notification.BASAL_VALUE_BELOW_MINIMUM, MainApp.gs(R.string.basalvaluebelowminimum), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(notification));
RxBus.INSTANCE.send(new EventNewNotification(notification));
if (callback != null)
callback.result(new PumpEnactResult().success(false).enacted(false).comment(MainApp.gs(R.string.basalvaluebelowminimum))).run();
return false;
}
}
MainApp.bus().post(new EventDismissNotification(Notification.BASAL_VALUE_BELOW_MINIMUM));
RxBus.INSTANCE.send(new EventDismissNotification(Notification.BASAL_VALUE_BELOW_MINIMUM));
// remove all unfinished
removeAll(Command.CommandType.BASALPROFILE);

View file

@ -93,7 +93,7 @@ public class QueueThread extends Thread {
SystemClock.sleep(1000);
//start over again once after watchdog barked
//Notification notification = new Notification(Notification.OLD_NSCLIENT, "Watchdog", Notification.URGENT);
//MainApp.bus().post(new EventNewNotification(notification));
//RxBus.INSTANCE.send(new EventNewNotification(notification));
connectionStartTime = lastCommandTime = System.currentTimeMillis();
pump.connect("watchdog");
} else {

View file

@ -10,8 +10,8 @@ import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.general.nsclient.data.NSAlarm;
import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification;
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification;
@ -41,11 +41,11 @@ public class NSAlarmReceiver extends BroadcastReceiver {
case Intents.ACTION_URGENT_ALARM:
Notification notification = new Notification(nsAlarm);
if (notification.isEnabled())
MainApp.bus().post(new EventNewNotification(notification));
RxBus.INSTANCE.send(new EventNewNotification(notification));
break;
case Intents.ACTION_CLEAR_ALARM:
MainApp.bus().post(new EventDismissNotification(Notification.NSALARM));
MainApp.bus().post(new EventDismissNotification(Notification.NSURGENTALARM));
RxBus.INSTANCE.send(new EventDismissNotification(Notification.NSALARM));
RxBus.INSTANCE.send(new EventDismissNotification(Notification.NSURGENTALARM));
break;
}
}

View file

@ -71,6 +71,10 @@ public class NetworkChangeReceiver extends BroadcastReceiver {
return lastEvent != null && lastEvent.wifiConnected;
}
public static boolean isConnected() {
return lastEvent != null && (lastEvent.wifiConnected || lastEvent.mobileConnected);
}
public static EventNetworkChange getLastEvent() {
return lastEvent;
}

View file

@ -16,15 +16,17 @@ import info.nightscout.androidaps.R;
import info.nightscout.androidaps.db.CareportalEvent;
import info.nightscout.androidaps.events.EventNsFood;
import info.nightscout.androidaps.events.EventNsTreatment;
import info.nightscout.androidaps.logging.BundleLogger;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.general.nsclient.data.NSDeviceStatus;
import info.nightscout.androidaps.plugins.general.nsclient.data.NSMbg;
import info.nightscout.androidaps.plugins.general.nsclient.data.NSSettingsStatus;
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification;
import info.nightscout.androidaps.plugins.general.smsCommunicator.SmsCommunicatorPlugin;
import info.nightscout.androidaps.plugins.profile.ns.NSProfilePlugin;
import info.nightscout.androidaps.plugins.pump.danaR.activities.DanaRNSHistorySync;
import info.nightscout.androidaps.plugins.general.smsCommunicator.SmsCommunicatorPlugin;
import info.nightscout.androidaps.plugins.source.SourceDexcomPlugin;
import info.nightscout.androidaps.plugins.source.SourceEversensePlugin;
import info.nightscout.androidaps.plugins.source.SourceGlimpPlugin;
@ -34,7 +36,6 @@ import info.nightscout.androidaps.plugins.source.SourcePoctechPlugin;
import info.nightscout.androidaps.plugins.source.SourceTomatoPlugin;
import info.nightscout.androidaps.plugins.source.SourceXdripPlugin;
import info.nightscout.androidaps.receivers.DataReceiver;
import info.nightscout.androidaps.logging.BundleLogger;
import info.nightscout.androidaps.utils.JsonHelper;
import info.nightscout.androidaps.utils.SP;
@ -100,7 +101,7 @@ public class DataService extends IntentService {
Intents.ACTION_REMOVED_TREATMENT.equals(action) ||
Intents.ACTION_NEW_CAL.equals(action) ||
Intents.ACTION_NEW_MBG.equals(action))
) {
) {
handleNewDataFromNSClient(intent);
} else if (Telephony.Sms.Intents.SMS_RECEIVED_ACTION.equals(action)) {
SmsCommunicatorPlugin.getPlugin().handleNewData(intent);
@ -254,7 +255,7 @@ public class DataService extends IntentService {
if (date > now - 15 * 60 * 1000L && !notes.isEmpty()
&& !enteredBy.equals(SP.getString("careportal_enteredby", "AndroidAPS"))) {
Notification announcement = new Notification(Notification.NSANNOUNCEMENT, notes, Notification.ANNOUNCEMENT, 60);
MainApp.bus().post(new EventNewNotification(announcement));
RxBus.INSTANCE.send(new EventNewNotification(announcement));
}
}
}

View file

@ -17,6 +17,7 @@ import androidx.core.content.ContextCompat;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification;
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification;
@ -56,7 +57,7 @@ public class AndroidPermission {
} catch (ActivityNotFoundException e) {
permission_battery_optimization_failed = true;
OKDialog.show(activity, MainApp.gs(R.string.permission), MainApp.gs(R.string.alert_dialog_permission_battery_optimization_failed), activity::recreate);
}
}
}
}
@ -84,18 +85,18 @@ public class AndroidPermission {
notification.action(R.string.request, () -> AndroidPermission.askForPermission(activity, new String[]{Manifest.permission.RECEIVE_SMS,
Manifest.permission.SEND_SMS,
Manifest.permission.RECEIVE_MMS}, AndroidPermission.CASE_SMS));
MainApp.bus().post(new EventNewNotification(notification));
RxBus.INSTANCE.send(new EventNewNotification(notification));
} else
MainApp.bus().post(new EventDismissNotification(Notification.PERMISSION_SMS));
RxBus.INSTANCE.send(new EventDismissNotification(Notification.PERMISSION_SMS));
// Following is a bug in Android 8
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.O) {
if (permissionNotGranted(activity, Manifest.permission.READ_PHONE_STATE)) {
NotificationWithAction notification = new NotificationWithAction(Notification.PERMISSION_PHONESTATE, MainApp.gs(R.string.smscommunicator_missingphonestatepermission), Notification.URGENT);
notification.action(R.string.request, () ->
AndroidPermission.askForPermission(activity, new String[]{Manifest.permission.READ_PHONE_STATE}, AndroidPermission.CASE_PHONE_STATE));
MainApp.bus().post(new EventNewNotification(notification));
RxBus.INSTANCE.send(new EventNewNotification(notification));
} else
MainApp.bus().post(new EventDismissNotification(Notification.PERMISSION_PHONESTATE));
RxBus.INSTANCE.send(new EventDismissNotification(Notification.PERMISSION_PHONESTATE));
}
}
}
@ -104,9 +105,9 @@ public class AndroidPermission {
if (permissionNotGranted(activity, Manifest.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS)) {
NotificationWithAction notification = new NotificationWithAction(Notification.PERMISSION_BATTERY, String.format(MainApp.gs(R.string.needwhitelisting), MainApp.gs(R.string.app_name)), Notification.URGENT);
notification.action(R.string.request, () -> AndroidPermission.askForPermission(activity, new String[]{Manifest.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS}, AndroidPermission.CASE_BATTERY));
MainApp.bus().post(new EventNewNotification(notification));
RxBus.INSTANCE.send(new EventNewNotification(notification));
} else
MainApp.bus().post(new EventDismissNotification(Notification.PERMISSION_BATTERY));
RxBus.INSTANCE.send(new EventDismissNotification(Notification.PERMISSION_BATTERY));
}
public static synchronized void notifyForStoragePermission(Activity activity) {
@ -114,17 +115,17 @@ public class AndroidPermission {
NotificationWithAction notification = new NotificationWithAction(Notification.PERMISSION_STORAGE, MainApp.gs(R.string.needstoragepermission), Notification.URGENT);
notification.action(R.string.request, () -> AndroidPermission.askForPermission(activity, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE}, AndroidPermission.CASE_STORAGE));
MainApp.bus().post(new EventNewNotification(notification));
RxBus.INSTANCE.send(new EventNewNotification(notification));
} else
MainApp.bus().post(new EventDismissNotification(Notification.PERMISSION_STORAGE));
RxBus.INSTANCE.send(new EventDismissNotification(Notification.PERMISSION_STORAGE));
}
public static synchronized void notifyForLocationPermissions(Activity activity) {
if (permissionNotGranted(activity, Manifest.permission.ACCESS_FINE_LOCATION)) {
NotificationWithAction notification = new NotificationWithAction(Notification.PERMISSION_LOCATION, MainApp.gs(R.string.needlocationpermission), Notification.URGENT);
notification.action(R.string.request, () -> AndroidPermission.askForPermission(activity, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, AndroidPermission.CASE_LOCATION));
MainApp.bus().post(new EventNewNotification(notification));
RxBus.INSTANCE.send(new EventNewNotification(notification));
} else
MainApp.bus().post(new EventDismissNotification(Notification.PERMISSION_LOCATION));
RxBus.INSTANCE.send(new EventDismissNotification(Notification.PERMISSION_LOCATION));
}
}

View file

@ -241,8 +241,10 @@ class BolusWizard @JvmOverloads constructor(val profile: Profile,
private fun confirmMessageAfterConstraints(pump: PumpInterface): String {
var confirmMessage = MainApp.gs(R.string.entertreatmentquestion)
if (insulinAfterConstraints > 0)
confirmMessage += "<br/>" + MainApp.gs(R.string.bolus) + ": " + "<font color='" + MainApp.gc(R.color.bolus) + "'>" + DecimalFormatter.toPumpSupportedBolus(insulinAfterConstraints) + "U" + "</font>"
if (insulinAfterConstraints > 0) {
val pct = if (percentageCorrection != 100.0) " (" + percentageCorrection.toInt() + "%)" else ""
confirmMessage += "<br/>" + MainApp.gs(R.string.bolus) + ": " + "<font color='" + MainApp.gc(R.color.bolus) + "'>" + DecimalFormatter.toPumpSupportedBolus(insulinAfterConstraints) + "U" + pct + "</font>"
}
if (carbs > 0) {
var timeShift = ""
if (carbTime > 0) {
@ -253,7 +255,7 @@ class BolusWizard @JvmOverloads constructor(val profile: Profile,
confirmMessage += "<br/>" + MainApp.gs(R.string.carbs) + ": " + "<font color='" + MainApp.gc(R.color.carbs) + "'>" + carbs + "g" + timeShift + "</font>"
}
if (insulinFromCOB > 0) {
confirmMessage += "<br/>" + MainApp.gs(R.string.insulinFromCob, MainApp.gc(R.color.cobAlert), cob, insulinFromCOB)
confirmMessage += "<br/>" + MainApp.gs(R.string.insulinFromCob, MainApp.gc(R.color.cobAlert), insulinFromBolusIOB + insulinFromBasalsIOB + insulinFromCOB + insulinFromBG)
val absorptionRate = IobCobCalculatorPlugin.getPlugin().slowAbsorptionPercentage(60)
if (absorptionRate > .25)
confirmMessage += "<br/>" + MainApp.gs(R.string.slowabsorptiondetected, MainApp.gc(R.color.cobAlert), (absorptionRate * 100).toInt())

View file

@ -10,9 +10,10 @@ import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.db.BgReading;
import info.nightscout.androidaps.db.DatabaseHelper;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin;
import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin;
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload;
import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification;
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification;
@ -43,13 +44,13 @@ public class LocalAlertUtils {
Notification n = new Notification(Notification.PUMP_UNREACHABLE, MainApp.gs(R.string.pump_unreachable), Notification.URGENT);
n.soundId = R.raw.alarm;
SP.putLong("nextPumpDisconnectedAlarm", System.currentTimeMillis() + pumpUnreachableThreshold());
MainApp.bus().post(new EventNewNotification(n));
RxBus.INSTANCE.send(new EventNewNotification(n));
if (SP.getBoolean(R.string.key_ns_create_announcements_from_errors, true)) {
NSUpload.uploadError(n.text);
}
}
if (!isStatusOutdated && !alarmTimeoutExpired)
MainApp.bus().post(new EventDismissNotification(Notification.PUMP_UNREACHABLE));
RxBus.INSTANCE.send(new EventDismissNotification(Notification.PUMP_UNREACHABLE));
}
/*Presnoozes the alarms with 5 minutes if no snooze exists.
@ -97,7 +98,7 @@ public class LocalAlertUtils {
Notification n = new Notification(Notification.BG_READINGS_MISSED, MainApp.gs(R.string.missed_bg_readings), Notification.URGENT);
n.soundId = R.raw.alarm;
SP.putLong("nextMissedReadingsAlarm", System.currentTimeMillis() + missedReadingsThreshold());
MainApp.bus().post(new EventNewNotification(n));
RxBus.INSTANCE.send(new EventNewNotification(n));
if (SP.getBoolean(R.string.key_ns_create_announcements_from_errors, true)) {
NSUpload.uploadError(n.text);
}

View file

@ -0,0 +1,227 @@
package info.nightscout.androidaps.utils;
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import android.os.SystemClock;
import android.util.Log;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
/**
* {@hide}
* <p>
* Simple SNTP client class for retrieving network time.
* <p>
* Sample usage:
* <pre>SntpClient client = new SntpClient();
* if (client.requestTime("time.foo.com")) {
* long now = client.getNtpTime() + SystemClock.elapsedRealtime() - client.getNtpTimeReference();
* }
* </pre>
*/
public class SntpClient {
private static final String TAG = "SntpClient";
//private static final int REFERENCE_TIME_OFFSET = 16;
private static final int ORIGINATE_TIME_OFFSET = 24;
private static final int RECEIVE_TIME_OFFSET = 32;
private static final int TRANSMIT_TIME_OFFSET = 40;
private static final int NTP_PACKET_SIZE = 48;
private static final int NTP_PORT = 123;
private static final int NTP_MODE_CLIENT = 3;
private static final int NTP_VERSION = 3;
// Number of seconds between Jan 1, 1900 and Jan 1, 1970
// 70 years plus 17 leap days
private static final long OFFSET_1900_TO_1970 = ((365L * 70L) + 17L) * 24L * 60L * 60L;
// system time computed from NTP server response
private static long mNtpTime;
// value of SystemClock.elapsedRealtime() corresponding to mNtpTime
private static long mNtpTimeReference;
// round trip time in milliseconds
private static long mRoundTripTime;
public static abstract class Callback implements Runnable {
public boolean networkConnected = false;
public boolean success = false;
public long time = 0;
}
public static synchronized void ntpTime(final Callback callback, boolean isConnected) {
callback.networkConnected = isConnected;
if (callback.networkConnected) {
new Thread(() -> doNtpTime(callback)).start();
} else {
callback.run();
}
}
static void doNtpTime(final Callback callback) {
callback.success = requestTime("time.google.com", 5000);
callback.time = getNtpTime() + SystemClock.elapsedRealtime() - getNtpTimeReference();
callback.run();
}
/**
* Sends an SNTP request to the given host and processes the response.
*
* @param host host name of the server.
* @param timeout network timeout in milliseconds.
* @return true if the transaction was successful.
*/
private static synchronized boolean requestTime(String host, int timeout) {
try {
DatagramSocket socket = new DatagramSocket();
socket.setSoTimeout(timeout);
InetAddress address = InetAddress.getByName(host);
byte[] buffer = new byte[NTP_PACKET_SIZE];
DatagramPacket request = new DatagramPacket(buffer, buffer.length, address, NTP_PORT);
// set mode = 3 (client) and version = 3
// mode is in low 3 bits of first byte
// version is in bits 3-5 of first byte
buffer[0] = NTP_MODE_CLIENT | (NTP_VERSION << 3);
// get current time and write it to the request packet
long requestTime = System.currentTimeMillis();
long requestTicks = SystemClock.elapsedRealtime();
writeTimeStamp(buffer, TRANSMIT_TIME_OFFSET, requestTime);
socket.send(request);
// read the response
DatagramPacket response = new DatagramPacket(buffer, buffer.length);
socket.receive(response);
long responseTicks = SystemClock.elapsedRealtime();
long responseTime = requestTime + (responseTicks - requestTicks);
socket.close();
// extract the results
long originateTime = readTimeStamp(buffer, ORIGINATE_TIME_OFFSET);
long receiveTime = readTimeStamp(buffer, RECEIVE_TIME_OFFSET);
long transmitTime = readTimeStamp(buffer, TRANSMIT_TIME_OFFSET);
long roundTripTime = responseTicks - requestTicks - (transmitTime - receiveTime);
// receiveTime = originateTime + transit + skew
// responseTime = transmitTime + transit - skew
// clockOffset = ((receiveTime - originateTime) + (transmitTime - responseTime))/2
// = ((originateTime + transit + skew - originateTime) +
// (transmitTime - (transmitTime + transit - skew)))/2
// = ((transit + skew) + (transmitTime - transmitTime - transit + skew))/2
// = (transit + skew - transit + skew)/2
// = (2 * skew)/2 = skew
long clockOffset = ((receiveTime - originateTime) + (transmitTime - responseTime)) / 2;
// if (Config.LOGD) Log.d(TAG, "round trip: " + roundTripTime + " ms");
// if (Config.LOGD) Log.d(TAG, "clock offset: " + clockOffset + " ms");
// save our results - use the times on this side of the network latency
// (response rather than request time)
mNtpTime = responseTime + clockOffset;
mNtpTimeReference = responseTicks;
mRoundTripTime = roundTripTime;
} catch (Exception e) {
Log.d(TAG, "request time failed: " + e);
return false;
}
return true;
}
/**
* Returns the time computed from the NTP transaction.
*
* @return time value computed from NTP server response.
*/
private static long getNtpTime() {
return mNtpTime;
}
/**
* Returns the reference clock value (value of SystemClock.elapsedRealtime())
* corresponding to the NTP time.
*
* @return reference clock corresponding to the NTP time.
*/
private static long getNtpTimeReference() {
return mNtpTimeReference;
}
/**
* Returns the round trip time of the NTP transaction
*
* @return round trip time in milliseconds.
*/
public long getRoundTripTime() {
return mRoundTripTime;
}
/**
* Reads an unsigned 32 bit big endian number from the given offset in the buffer.
*/
private static long read32(byte[] buffer, int offset) {
byte b0 = buffer[offset];
byte b1 = buffer[offset + 1];
byte b2 = buffer[offset + 2];
byte b3 = buffer[offset + 3];
// convert signed bytes to unsigned values
int i0 = ((b0 & 0x80) == 0x80 ? (b0 & 0x7F) + 0x80 : b0);
int i1 = ((b1 & 0x80) == 0x80 ? (b1 & 0x7F) + 0x80 : b1);
int i2 = ((b2 & 0x80) == 0x80 ? (b2 & 0x7F) + 0x80 : b2);
int i3 = ((b3 & 0x80) == 0x80 ? (b3 & 0x7F) + 0x80 : b3);
return ((long) i0 << 24) + ((long) i1 << 16) + ((long) i2 << 8) + (long) i3;
}
/**
* Reads the NTP time stamp at the given offset in the buffer and returns
* it as a system time (milliseconds since January 1, 1970).
*/
private static long readTimeStamp(byte[] buffer, int offset) {
long seconds = read32(buffer, offset);
long fraction = read32(buffer, offset + 4);
return ((seconds - OFFSET_1900_TO_1970) * 1000) + ((fraction * 1000L) / 0x100000000L);
}
/**
* Writes system time (milliseconds since January 1, 1970) as an NTP time stamp
* at the given offset in the buffer.
*/
private static void writeTimeStamp(byte[] buffer, int offset, long time) {
long seconds = time / 1000L;
long milliseconds = time - seconds * 1000L;
seconds += OFFSET_1900_TO_1970;
// write seconds in big endian format
buffer[offset++] = (byte) (seconds >> 24);
buffer[offset++] = (byte) (seconds >> 16);
buffer[offset++] = (byte) (seconds >> 8);
buffer[offset++] = (byte) (seconds >> 0);
long fraction = milliseconds * 0x100000000L / 1000L;
// write fraction in big endian format
buffer[offset++] = (byte) (fraction >> 24);
buffer[offset++] = (byte) (fraction >> 16);
buffer[offset++] = (byte) (fraction >> 8);
// low order bits should be random data
buffer[offset++] = (byte) (Math.random() * 255.0);
}
}

View file

@ -6,29 +6,20 @@ import android.os.Handler;
import android.os.Looper;
import android.widget.Toast;
import androidx.annotation.IdRes;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification;
import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification;
public class ToastUtils {
public static void showToastInUiThread(final Context ctx,
final int stringId) {
public static void showToastInUiThread(final Context ctx, final int stringId) {
showToastInUiThread(ctx, MainApp.gs(stringId));
}
public static void showToastInUiThread(final Context ctx,
final String string) {
public static void showToastInUiThread(final Context ctx, final String string) {
Handler mainThread = new Handler(Looper.getMainLooper());
mainThread.post(new Runnable() {
@Override
public void run() {
Toast.makeText(ctx, string, Toast.LENGTH_SHORT).show();
}
});
mainThread.post(() -> Toast.makeText(ctx, string, Toast.LENGTH_SHORT).show());
}
public static void showToastInUiThread(final Context ctx,
@ -36,23 +27,13 @@ public class ToastUtils {
showToastInUiThread(ctx, string);
playSound(ctx, soundID);
new Thread(new Runnable() {
@Override
public void run() {
Notification notification = new Notification(Notification.TOAST_ALARM, string, Notification.URGENT);
MainApp.bus().post(new EventNewNotification(notification));
}
}).start();
Notification notification = new Notification(Notification.TOAST_ALARM, string, Notification.URGENT);
RxBus.INSTANCE.send(new EventNewNotification(notification));
}
private static void playSound(final Context ctx, final int soundID) {
final MediaPlayer soundMP = MediaPlayer.create(ctx, soundID);
soundMP.start();
soundMP.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
soundMP.setOnCompletionListener(MediaPlayer::release);
}
}

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