Merge branch 'display-carsReq' of github.com:twain47/AndroidAPS into carbs-required

This commit is contained in:
Tim Gunn 2020-05-03 16:45:45 +12:00
commit a1450feb2b
No known key found for this signature in database
GPG key ID: C9BC1E9D0D0AED8C
11 changed files with 204 additions and 37 deletions

View file

@ -121,6 +121,9 @@
<!-- Receiver keepalive, scheduled every 30 min --> <!-- Receiver keepalive, scheduled every 30 min -->
<receiver android:name=".receivers.KeepAliveReceiver" /> <receiver android:name=".receivers.KeepAliveReceiver" />
<!-- Receive ignore 5m, 15m, 30m requests for carb notifications -->
<receiver android:name=".plugins.aps.loop.CarbSuggestionReceiver"></receiver>
<!-- Auto start --> <!-- Auto start -->
<receiver <receiver
android:name=".receivers.AutoStartReceiver" android:name=".receivers.AutoStartReceiver"

View file

@ -877,8 +877,10 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_
console.error("naive_eventualBG:",naive_eventualBG,"bgUndershoot:",bgUndershoot,"zeroTempDuration:",zeroTempDuration,"zeroTempEffect:",zeroTempEffect,"carbsReq:",carbsReq); console.error("naive_eventualBG:",naive_eventualBG,"bgUndershoot:",bgUndershoot,"zeroTempDuration:",zeroTempDuration,"zeroTempEffect:",zeroTempEffect,"carbsReq:",carbsReq);
if ( carbsReq >= profile.carbsReqThreshold && minutesAboveThreshold <= 45 ) { if ( carbsReq >= profile.carbsReqThreshold && minutesAboveThreshold <= 45 ) {
rT.carbsReq = carbsReq; rT.carbsReq = carbsReq;
rT.carbsReqWithin = minutesAboveThreshold;
rT.reason += carbsReq + " add'l carbs req w/in " + minutesAboveThreshold + "m; "; rT.reason += carbsReq + " add'l carbs req w/in " + minutesAboveThreshold + "m; ";
} }
// don't low glucose suspend if IOB is already super negative and BG is rising faster than predicted // don't low glucose suspend if IOB is already super negative and BG is rising faster than predicted
if (bg < threshold && iob_data.iob < -profile.current_basal*20/60 && minDelta > 0 && minDelta > expectedDelta) { if (bg < threshold && iob_data.iob < -profile.current_basal*20/60 && minDelta > 0 && minDelta > expectedDelta) {
rT.reason += "IOB "+iob_data.iob+" < " + round(-profile.current_basal*20/60,2); rT.reason += "IOB "+iob_data.iob+" < " + round(-profile.current_basal*20/60,2);

View file

@ -4,8 +4,10 @@ import dagger.Module
import dagger.android.ContributesAndroidInjector import dagger.android.ContributesAndroidInjector
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkBluetoothStateReceiver import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkBluetoothStateReceiver
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkBroadcastReceiver import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkBroadcastReceiver
import info.nightscout.androidaps.plugins.aps.loop.CarbSuggestionReceiver
import info.nightscout.androidaps.receivers.* import info.nightscout.androidaps.receivers.*
@Module @Module
@Suppress("unused") @Suppress("unused")
abstract class ReceiversModule { abstract class ReceiversModule {
@ -18,6 +20,6 @@ abstract class ReceiversModule {
@ContributesAndroidInjector abstract fun contributesRileyLinkBluetoothStateReceiver(): RileyLinkBluetoothStateReceiver @ContributesAndroidInjector abstract fun contributesRileyLinkBluetoothStateReceiver(): RileyLinkBluetoothStateReceiver
@ContributesAndroidInjector abstract fun contributesSmsReceiver(): SmsReceiver @ContributesAndroidInjector abstract fun contributesSmsReceiver(): SmsReceiver
@ContributesAndroidInjector abstract fun contributesTimeDateOrTZChangeReceiver(): TimeDateOrTZChangeReceiver @ContributesAndroidInjector abstract fun contributesTimeDateOrTZChangeReceiver(): TimeDateOrTZChangeReceiver
@ContributesAndroidInjector abstract fun contributesCarbSuggestionReceiver(): CarbSuggestionReceiver
@ContributesAndroidInjector abstract fun contributesRileyLinkBroadcastReceiver(): RileyLinkBroadcastReceiver @ContributesAndroidInjector abstract fun contributesRileyLinkBroadcastReceiver(): RileyLinkBroadcastReceiver
} }

View file

@ -63,6 +63,9 @@ public class APSResult {
public double smb = 0d; // super micro bolus in units public double smb = 0d; // super micro bolus in units
public long deliverAt = 0; public long deliverAt = 0;
public int carbsReq = 0;
public int carbsReqWithin = 0;
public Constraint<Double> inputConstraints; public Constraint<Double> inputConstraints;
public Constraint<Double> rateConstraint; public Constraint<Double> rateConstraint;
@ -99,6 +102,10 @@ public class APSResult {
return this; return this;
} }
public String getCarbsRequiredText() {
return String.format(resourceHelper.gs(R.string.carbsreq), carbsReq, carbsReqWithin);
}
@Override @Override
public String toString() { public String toString() {
final PumpInterface pump = activePlugin.getActivePump(); final PumpInterface pump = activePlugin.getActivePump();
@ -122,10 +129,19 @@ public class APSResult {
if (smb != 0) if (smb != 0)
ret += ("SMB: " + DecimalFormatter.toPumpSupportedBolus(smb, activePlugin.getActivePump()) + " U\n"); ret += ("SMB: " + DecimalFormatter.toPumpSupportedBolus(smb, activePlugin.getActivePump()) + " U\n");
if (isCarbsRequired()) {
ret += getCarbsRequiredText()+"\n";
}
// reason // reason
ret += resourceHelper.gs(R.string.reason) + ": " + reason; ret += resourceHelper.gs(R.string.reason) + ": " + reason;
return ret; return ret;
} else }
if (isCarbsRequired()) {
return getCarbsRequiredText();
}
return resourceHelper.gs(R.string.nochangerequested); return resourceHelper.gs(R.string.nochangerequested);
} }
@ -151,10 +167,19 @@ public class APSResult {
if (smb != 0) if (smb != 0)
ret += ("<b>" + "SMB" + "</b>: " + DecimalFormatter.toPumpSupportedBolus(smb, activePlugin.getActivePump()) + " U<br>"); ret += ("<b>" + "SMB" + "</b>: " + DecimalFormatter.toPumpSupportedBolus(smb, activePlugin.getActivePump()) + " U<br>");
if (isCarbsRequired()) {
ret += getCarbsRequiredText()+"<br>";
}
// reason // reason
ret += "<b>" + resourceHelper.gs(R.string.reason) + "</b>: " + reason.replace("<", "&lt;").replace(">", "&gt;"); ret += "<b>" + resourceHelper.gs(R.string.reason) + "</b>: " + reason.replace("<", "&lt;").replace(">", "&gt;");
return Html.fromHtml(ret); return Html.fromHtml(ret);
} else }
if (isCarbsRequired()) {
return Html.fromHtml(getCarbsRequiredText());
}
return Html.fromHtml(resourceHelper.gs(R.string.nochangerequested)); return Html.fromHtml(resourceHelper.gs(R.string.nochangerequested));
} }
@ -184,6 +209,8 @@ public class APSResult {
newResult.smbConstraint = smbConstraint; newResult.smbConstraint = smbConstraint;
newResult.percent = percent; newResult.percent = percent;
newResult.usePercent = usePercent; newResult.usePercent = usePercent;
newResult.carbsReq = carbsReq;
newResult.carbsReqWithin = carbsReqWithin;
} }
@ -298,6 +325,10 @@ public class APSResult {
return latest; return latest;
} }
public boolean isCarbsRequired() {
return carbsReq > 0;
}
public boolean isChangeRequested() { public boolean isChangeRequested() {
Constraint<Boolean> closedLoopEnabled = constraintChecker.isClosedLoopAllowed(); Constraint<Boolean> closedLoopEnabled = constraintChecker.isClosedLoopAllowed();
// closed loop mode: handle change at driver level // closed loop mode: handle change at driver level

View file

@ -0,0 +1,20 @@
package info.nightscout.androidaps.plugins.aps.loop;
import android.content.Context;
import android.content.Intent;
import javax.inject.Inject;
import dagger.android.DaggerBroadcastReceiver;
public class CarbSuggestionReceiver extends DaggerBroadcastReceiver {
@Inject LoopPlugin loopPlugin;
@Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
int duartion = intent.getIntExtra("ignoreDuration", 5);
loopPlugin.disableCarbSuggestions(duartion);
}
}

View file

@ -101,6 +101,8 @@ public class LoopPlugin extends PluginBase {
private boolean isSuperBolus; private boolean isSuperBolus;
private boolean isDisconnected; private boolean isDisconnected;
private long carbsSuggestionsSuspendedUntil = 0;
public class LastRun { public class LastRun {
public APSResult request = null; public APSResult request = null;
public APSResult constraintsProcessed = null; public APSResult constraintsProcessed = null;
@ -431,6 +433,58 @@ public class LoopPlugin extends PluginBase {
Constraint<Boolean> closedLoopEnabled = constraintChecker.isClosedLoopAllowed(); Constraint<Boolean> closedLoopEnabled = constraintChecker.isClosedLoopAllowed();
if (closedLoopEnabled.value()) { if (closedLoopEnabled.value()) {
if (allowNotification) {
if (resultAfterConstraints.isCarbsRequired()
&& resultAfterConstraints.carbsReq >= sp.getInt(R.string.key_smb_enable_carbs_suggestions_threshold, 0)
&& carbsSuggestionsSuspendedUntil < System.currentTimeMillis()) {
Intent intentAction5m = new Intent(context, CarbSuggestionReceiver.class);
intentAction5m.putExtra("ignoreDuration",5);
PendingIntent pendingIntent5m = PendingIntent.getBroadcast(context,1, intentAction5m,PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Action actionIgnore5m = new
NotificationCompat.Action(R.drawable.ic_notif_aaps, "Ignore 5m", pendingIntent5m);
Intent intentAction15m = new Intent(context, CarbSuggestionReceiver.class);
intentAction15m.putExtra("ignoreDuration",15);
PendingIntent pendingIntent15m = PendingIntent.getBroadcast(context,1, intentAction15m,PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Action actionIgnore15m = new
NotificationCompat.Action(R.drawable.ic_notif_aaps, "Ignore 15m", pendingIntent15m);
Intent intentAction30m = new Intent(context, CarbSuggestionReceiver.class);
intentAction30m.putExtra("ignoreDuration",30);
PendingIntent pendingIntent30m = PendingIntent.getBroadcast(context,1, intentAction30m,PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Action actionIgnore30m = new
NotificationCompat.Action(R.drawable.ic_notif_aaps, "Ignore 30m", pendingIntent30m);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID);
builder.setSmallIcon(R.drawable.notif_icon)
.setContentTitle(resourceHelper.gs(R.string.carbssuggestion))
.setContentText(resultAfterConstraints.getCarbsRequiredText())
.setAutoCancel(true)
.setPriority(Notification.PRIORITY_MAX)
.setCategory(Notification.CATEGORY_ALARM)
.addAction(actionIgnore5m)
.addAction(actionIgnore15m)
.addAction(actionIgnore30m)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setVibrate(new long[]{1000, 1000, 1000, 1000, 1000});
NotificationManager mNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotificationManager.notify(Constants.notificationID, builder.build());
rxBus.send(new EventNewOpenLoopNotification());
// Send to Wear
actionStringHandler.get().handleInitiate("changeRequest");
} else {
dismissSuggestion();
}
}
if (resultAfterConstraints.isChangeRequested() if (resultAfterConstraints.isChangeRequested()
&& !commandQueue.bolusInQueue() && !commandQueue.bolusInQueue()
&& !commandQueue.isRunning(Command.CommandType.BOLUS)) { && !commandQueue.isRunning(Command.CommandType.BOLUS)) {
@ -489,7 +543,24 @@ public class LoopPlugin extends PluginBase {
if (sp.getBoolean("wearcontrol", false)) { if (sp.getBoolean("wearcontrol", false)) {
builder.setLocalOnly(true); builder.setLocalOnly(true);
} }
presentSuggestion(builder);
} else if (allowNotification) {
dismissSuggestion();
}
}
rxBus.send(new EventLoopUpdateGui());
} finally {
getAapsLogger().debug(LTag.APS, "invoke end");
}
}
public void disableCarbSuggestions(int duartionMinutes) {
carbsSuggestionsSuspendedUntil = System.currentTimeMillis() + (duartionMinutes*60*1000);
dismissSuggestion();
}
private void presentSuggestion(NotificationCompat.Builder builder) {
// Creates an explicit intent for an Activity in your app // Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(context, MainActivity.class); Intent resultIntent = new Intent(context, MainActivity.class);
@ -513,20 +584,15 @@ public class LoopPlugin extends PluginBase {
// Send to Wear // Send to Wear
actionStringHandler.get().handleInitiate("changeRequest"); actionStringHandler.get().handleInitiate("changeRequest");
} else if (allowNotification) { }
private void dismissSuggestion() {
// dismiss notifications // dismiss notifications
NotificationManager notificationManager = NotificationManager notificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(Constants.notificationID); notificationManager.cancel(Constants.notificationID);
actionStringHandler.get().handleInitiate("cancelChangeRequest"); actionStringHandler.get().handleInitiate("cancelChangeRequest");
} }
}
rxBus.send(new EventLoopUpdateGui());
} finally {
getAapsLogger().debug(LTag.APS, "invoke end");
}
}
public void acceptChangeRequest() { public void acceptChangeRequest() {
Profile profile = profileFunction.getProfile(); Profile profile = profileFunction.getProfile();

View file

@ -4,10 +4,11 @@ import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import dagger.android.HasAndroidInjector; import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.plugins.aps.loop.APSResult; import info.nightscout.androidaps.plugins.aps.loop.APSResult;
import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.SP;
public class DetermineBasalResultSMB extends APSResult { public class DetermineBasalResultSMB extends APSResult {
@ -33,7 +34,11 @@ public class DetermineBasalResultSMB extends APSResult {
if (result.has("eventualBG")) eventualBG = result.getDouble("eventualBG"); if (result.has("eventualBG")) eventualBG = result.getDouble("eventualBG");
if (result.has("snoozeBG")) snoozeBG = result.getDouble("snoozeBG"); if (result.has("snoozeBG")) snoozeBG = result.getDouble("snoozeBG");
//if (result.has("insulinReq")) insulinReq = result.getDouble("insulinReq"); //if (result.has("insulinReq")) insulinReq = result.getDouble("insulinReq");
//if (result.has("carbsReq")) carbsReq = result.getDouble("carbsReq");
if (SP.getBoolean(R.string.key_smb_enable_carbs_suggestions, false)) {
if (result.has("carbsReq")) carbsReq = result.getInt("carbsReq");
if (result.has("carbsReqWithin")) carbsReqWithin = result.getInt("carbsReqWithin");
}
if (result.has("rate") && result.has("duration")) { if (result.has("rate") && result.has("duration")) {
tempBasalRequested = true; tempBasalRequested = true;

View file

@ -742,6 +742,15 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
overview_cob?.text = cobText overview_cob?.text = cobText
val lastRun = loopPlugin.lastRun val lastRun = loopPlugin.lastRun
if (Config.APS && lastRun?.constraintsProcessed != null && lastRun?.constraintsProcessed.carbsReq > 0) {
overview_cob_required.visibility = View.VISIBLE
var carbsRequiredString: String = String.format(resourceHelper.gs(R.string.overview_carbs_required), lastRun?.constraintsProcessed?.carbsReq, lastRun?.constraintsProcessed?.carbsReqWithin)
overview_cob_required.text = carbsRequiredString
} else {
overview_cob_required.visibility = View.GONE
}
val predictionsAvailable = if (Config.APS) lastRun?.request?.hasPredictions == true else Config.NSCLIENT val predictionsAvailable = if (Config.APS) lastRun?.request?.hasPredictions == true else Config.NSCLIENT
// pump status from ns // pump status from ns

View file

@ -266,6 +266,18 @@
app:layout_constraintBottom_toBottomOf="@+id/overview_cob_label" app:layout_constraintBottom_toBottomOf="@+id/overview_cob_label"
app:layout_constraintStart_toEndOf="@+id/overview_cob_colon" /> app:layout_constraintStart_toEndOf="@+id/overview_cob_colon" />
<TextView
android:id="@+id/overview_cob_required"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:text="@string/cob_required"
android:textSize="16sp"
android:textStyle="bold"
android:textColor="@color/cobAlert"
app:layout_constraintBottom_toBottomOf="@+id/overview_cob_label"
app:layout_constraintStart_toEndOf="@+id/overview_cob" />
<!-- right side basal --> <!-- right side basal -->
<TextView <TextView
android:id="@+id/overview_basebasal_label" android:id="@+id/overview_basebasal_label"

View file

@ -194,6 +194,8 @@
<string name="lgs">LGS</string> <string name="lgs">LGS</string>
<string name="openloop_newsuggestion">New suggestion available</string> <string name="openloop_newsuggestion">New suggestion available</string>
<string name="carbssuggestion">Carbs Suggestion</string>
<string name="unsupportedclientver">Unsupported version of NSClient</string>
<string name="unsupportednsversion">Unsupported version of Nightscout</string> <string name="unsupportednsversion">Unsupported version of Nightscout</string>
<string name="loopdisabled">LOOP DISABLED BY CONSTRAINTS</string> <string name="loopdisabled">LOOP DISABLED BY CONSTRAINTS</string>
<string name="treatments_wizard_basaliob_label">Basal IOB</string> <string name="treatments_wizard_basaliob_label">Basal IOB</string>
@ -324,6 +326,7 @@
<string name="percent">Percent</string> <string name="percent">Percent</string>
<string name="absolute">Absolute</string> <string name="absolute">Absolute</string>
<string name="canceltemp">Cancel temp basal</string> <string name="canceltemp">Cancel temp basal</string>
<string name="carbsreq">"%dg Additional Carbs Required Within %d Minutes</string>
<string name="smscommunicator">SMS Communicator</string> <string name="smscommunicator">SMS Communicator</string>
<string name="waitingforpumpresult">Waiting for result</string> <string name="waitingforpumpresult">Waiting for result</string>
<string name="smscommunicator_allowednumbers">Allowed phone numbers</string> <string name="smscommunicator_allowednumbers">Allowed phone numbers</string>
@ -774,10 +777,16 @@
<string name="smb_shortname">SMB</string> <string name="smb_shortname">SMB</string>
<string name="key_use_smb" translatable="false">use_smb</string> <string name="key_use_smb" translatable="false">use_smb</string>
<string name="key_use_uam" translatable="false">use_uam</string> <string name="key_use_uam" translatable="false">use_uam</string>
<string name="key_smb_enable_carbs_suggestions" translatable="false">key_smb_enable_carbs_suggestions</string>
<string name="key_smb_enable_carbs_suggestions_threshold" translatable="false">key_smb_enable_carbs_suggestions_threshold</string>
<string name="enableuam">Enable UAM</string> <string name="enableuam">Enable UAM</string>
<string name="enablesmb">Enable SMB</string> <string name="enablesmb">Enable SMB</string>
<string name="enablecarbssuggestions">Enable Carbs Suggestions</string>
<string name="enable_carbs_suggestions_threshold">Minimum Carbs Required For Suggestion</string>
<string name="enable_carbs_suggestions_threshold_summary">Minimum grams of carbs to display a carbs suggestion alert. Carbs suggestions below this number will not trigger a notification.</string>
<string name="enablesmb_summary">Use Super Micro Boluses instead of temp basal for faster action</string> <string name="enablesmb_summary">Use Super Micro Boluses instead of temp basal for faster action</string>
<string name="enableuam_summary">Detection of Unannounced meals</string> <string name="enableuam_summary">Detection of Unannounced meals</string>
<string name="enablecarbssuggestions_summary">Enable carbs suggestions when BG is predicted to go below threshold</string>
<string name="key_insulin_oref_peak" translatable="false">insulin_oref_peak</string> <string name="key_insulin_oref_peak" translatable="false">insulin_oref_peak</string>
<string name="insulin_oref_peak">IOB Curve Peak Time</string> <string name="insulin_oref_peak">IOB Curve Peak Time</string>
<string name="insulin_peak_time">Peak Time [min]</string> <string name="insulin_peak_time">Peak Time [min]</string>
@ -1828,4 +1837,6 @@
<string name="key_statuslights_copy_ns" translatable="false">statuslights_copy_ns</string> <string name="key_statuslights_copy_ns" translatable="false">statuslights_copy_ns</string>
<string name="copyexistingvalues">Copy NS settings (if exists)?</string> <string name="copyexistingvalues">Copy NS settings (if exists)?</string>
<string name="key_statuslights_overview_advanced" translatable="false">statuslights_overview_advanced</string> <string name="key_statuslights_overview_advanced" translatable="false">statuslights_overview_advanced</string>
<string name="cob_required">(20g needed in 45min)</string>
<string name="overview_carbs_required">(%dg needed in %dmin)</string>
</resources> </resources>

View file

@ -143,6 +143,12 @@
android:summary="@string/low_temptarget_lowers_sensitivity_summary" android:summary="@string/low_temptarget_lowers_sensitivity_summary"
android:title="@string/low_temptarget_lowers_sensitivity_title" /> android:title="@string/low_temptarget_lowers_sensitivity_title" />
<SwitchPreference
android:defaultValue="false"
android:key="@string/key_smb_enable_carbs_suggestions"
android:summary="@string/enablecarbssuggestions_summary"
android:title="@string/enablecarbssuggestions" />
<info.nightscout.androidaps.utils.textValidator.ValidatingEditTextPreference <info.nightscout.androidaps.utils.textValidator.ValidatingEditTextPreference
android:key="@string/key_carbsReqThreshold" android:key="@string/key_carbsReqThreshold"
android:title="@string/carbsReqThreshold" android:title="@string/carbsReqThreshold"