This commit is contained in:
Milos Kozak 2019-11-21 09:01:52 +01:00
commit 64faea691f
15 changed files with 118 additions and 149 deletions

View file

@ -22,7 +22,7 @@ import info.nightscout.androidaps.plugins.general.overview.notifications.Notific
public class DstHelperPlugin extends PluginBase implements ConstraintsInterface { public class DstHelperPlugin extends PluginBase implements ConstraintsInterface {
public static final int DISABLE_TIMEFRAME_HOURS = -3; public static final int DISABLE_TIMEFRAME_HOURS = -3;
public static final int WARN_PRIOR_TIMEFRAME_HOURS = 24; public static final int WARN_PRIOR_TIMEFRAME_HOURS = 12;
private static Logger log = LoggerFactory.getLogger(L.CONSTRAINTS); private static Logger log = LoggerFactory.getLogger(L.CONSTRAINTS);
static DstHelperPlugin plugin = null; static DstHelperPlugin plugin = null;

View file

@ -204,7 +204,7 @@ class ObjectivesFragment : Fragment() {
holder.accomplished.setTextColor(-0x3e3e3f) holder.accomplished.setTextColor(-0x3e3e3f)
holder.verify.setOnClickListener { holder.verify.setOnClickListener {
holder.verify.visibility = View.INVISIBLE holder.verify.visibility = View.INVISIBLE
NetworkChangeReceiver.fetch() NetworkChangeReceiver.grabNetworkStatus(context)
if (objectives_fake.isChecked) { if (objectives_fake.isChecked) {
objective.accomplishedOn = DateUtil.now() objective.accomplishedOn = DateUtil.now()
scrollToCurrentObjective() scrollToCurrentObjective()
@ -236,7 +236,7 @@ class ObjectivesFragment : Fragment() {
} }
holder.start.setOnClickListener { holder.start.setOnClickListener {
holder.start.visibility = View.INVISIBLE holder.start.visibility = View.INVISIBLE
NetworkChangeReceiver.fetch() NetworkChangeReceiver.grabNetworkStatus(context)
if (objectives_fake.isChecked) { if (objectives_fake.isChecked) {
objective.startedOn = DateUtil.now() objective.startedOn = DateUtil.now()
scrollToCurrentObjective() scrollToCurrentObjective()

View file

@ -89,7 +89,7 @@ public class NSClientPlugin extends PluginBase {
} }
nsClientReceiverDelegate = nsClientReceiverDelegate =
new NsClientReceiverDelegate(MainApp.instance().getApplicationContext()); new NsClientReceiverDelegate();
} }
public boolean isAllowed() { public boolean isAllowed() {
@ -104,7 +104,7 @@ public class NSClientPlugin extends PluginBase {
context.bindService(intent, mConnection, Context.BIND_AUTO_CREATE); context.bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
super.onStart(); super.onStart();
nsClientReceiverDelegate.registerReceivers(); nsClientReceiverDelegate.grabReceiversState();
disposable.add(RxBus.INSTANCE disposable.add(RxBus.INSTANCE
.toObservable(EventNSClientStatus.class) .toObservable(EventNSClientStatus.class)
.observeOn(Schedulers.io()) .observeOn(Schedulers.io())
@ -129,7 +129,6 @@ public class NSClientPlugin extends PluginBase {
.subscribe(event -> { .subscribe(event -> {
if (nsClientService != null) { if (nsClientService != null) {
MainApp.instance().getApplicationContext().unbindService(mConnection); MainApp.instance().getApplicationContext().unbindService(mConnection);
nsClientReceiverDelegate.unregisterReceivers();
} }
}, FabricPrivacy::logException) }, FabricPrivacy::logException)
); );
@ -152,7 +151,6 @@ public class NSClientPlugin extends PluginBase {
@Override @Override
protected void onStop() { protected void onStop() {
MainApp.instance().getApplicationContext().unbindService(mConnection); MainApp.instance().getApplicationContext().unbindService(mConnection);
nsClientReceiverDelegate.unregisterReceivers();
disposable.clear(); disposable.clear();
super.onStop(); super.onStop();
} }

View file

@ -18,44 +18,19 @@ import info.nightscout.androidaps.utils.SP;
class NsClientReceiverDelegate { class NsClientReceiverDelegate {
private final Context context;
private NetworkChangeReceiver networkChangeReceiver = new NetworkChangeReceiver();
private ChargingStateReceiver chargingStateReceiver = new ChargingStateReceiver();
private boolean allowedChargingState = true; private boolean allowedChargingState = true;
private boolean allowedNetworkState = true; private boolean allowedNetworkState = true;
boolean allowed = true; boolean allowed = true;
NsClientReceiverDelegate(Context context) { void grabReceiversState() {
this.context = context;
}
void registerReceivers() {
Context context = MainApp.instance().getApplicationContext(); Context context = MainApp.instance().getApplicationContext();
// register NetworkChangeReceiver --> https://developer.android.com/training/monitoring-device-state/connectivity-monitoring.html
// Nougat is not providing Connectivity-Action anymore ;-(
context.registerReceiver(networkChangeReceiver,
new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
context.registerReceiver(networkChangeReceiver,
new IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION));
EventNetworkChange event = networkChangeReceiver.grabNetworkStatus(context); EventNetworkChange event = NetworkChangeReceiver.grabNetworkStatus(context);
if (event != null) if (event != null) RxBus.INSTANCE.send(event);
RxBus.INSTANCE.send(event);
context.registerReceiver(chargingStateReceiver, EventChargingState eventChargingState = ChargingStateReceiver.grabChargingState(context);
new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); if (eventChargingState != null) RxBus.INSTANCE.send(eventChargingState);
EventChargingState eventChargingState = chargingStateReceiver.grabChargingState(context);
if (eventChargingState != null)
RxBus.INSTANCE.send(eventChargingState);
}
void unregisterReceivers() {
context.unregisterReceiver(networkChangeReceiver);
context.unregisterReceiver(chargingStateReceiver);
} }
void onStatusEvent(EventPreferenceChange ev) { void onStatusEvent(EventPreferenceChange ev) {
@ -63,11 +38,11 @@ class NsClientReceiverDelegate {
ev.isChanged(R.string.key_ns_wifi_ssids) || ev.isChanged(R.string.key_ns_wifi_ssids) ||
ev.isChanged(R.string.key_ns_allowroaming) ev.isChanged(R.string.key_ns_allowroaming)
) { ) {
EventNetworkChange event = networkChangeReceiver.grabNetworkStatus(MainApp.instance().getApplicationContext()); EventNetworkChange event = NetworkChangeReceiver.grabNetworkStatus(MainApp.instance().getApplicationContext());
if (event != null) if (event != null)
RxBus.INSTANCE.send(event); RxBus.INSTANCE.send(event);
} else if (ev.isChanged(R.string.key_ns_chargingonly)) { } else if (ev.isChanged(R.string.key_ns_chargingonly)) {
EventChargingState event = chargingStateReceiver.grabChargingState(MainApp.instance().getApplicationContext()); EventChargingState event = ChargingStateReceiver.grabChargingState(MainApp.instance().getApplicationContext());
if (event != null) if (event != null)
RxBus.INSTANCE.send(event); RxBus.INSTANCE.send(event);
} }
@ -91,7 +66,7 @@ class NsClientReceiverDelegate {
} }
} }
void processStateChange() { private void processStateChange() {
boolean newAllowedState = allowedChargingState && allowedNetworkState; boolean newAllowedState = allowedChargingState && allowedNetworkState;
if (newAllowedState != allowed) { if (newAllowedState != allowed) {
allowed = newAllowedState; allowed = newAllowedState;
@ -101,7 +76,6 @@ class NsClientReceiverDelegate {
boolean calculateStatus(final EventChargingState ev) { boolean calculateStatus(final EventChargingState ev) {
boolean chargingOnly = SP.getBoolean(R.string.key_ns_chargingonly, false); boolean chargingOnly = SP.getBoolean(R.string.key_ns_chargingonly, false);
boolean newAllowedState = true; boolean newAllowedState = true;
if (!ev.isCharging() && chargingOnly) { if (!ev.isCharging() && chargingOnly) {
@ -129,8 +103,6 @@ class NsClientReceiverDelegate {
} }
} }
return newAllowedState; return newAllowedState;
} }
} }

View file

@ -48,6 +48,7 @@ import info.nightscout.androidaps.plugins.general.overview.dialogs.ErrorHelperAc
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification; import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification; import info.nightscout.androidaps.plugins.general.overview.notifications.Notification;
import info.nightscout.androidaps.plugins.pump.common.PumpPluginAbstract; import info.nightscout.androidaps.plugins.pump.common.PumpPluginAbstract;
import info.nightscout.androidaps.plugins.pump.common.bolusInfo.DetailedBolusInfoStorage;
import info.nightscout.androidaps.plugins.pump.common.defs.PumpDriverState; import info.nightscout.androidaps.plugins.pump.common.defs.PumpDriverState;
import info.nightscout.androidaps.plugins.pump.common.defs.PumpType; import info.nightscout.androidaps.plugins.pump.common.defs.PumpType;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkConst; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkConst;
@ -372,7 +373,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
refreshAnyStatusThatNeedsToBeRefreshed(); refreshAnyStatusThatNeedsToBeRefreshed();
} }
RxBus.INSTANCE.send(new EventMedtronicPumpValuesChanged()); RxBus.INSTANCE.send(new EventMedtronicPumpValuesChanged());
} }
@ -386,7 +387,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
RileyLinkServiceState rileyLinkServiceState = MedtronicUtil.getServiceState(); RileyLinkServiceState rileyLinkServiceState = MedtronicUtil.getServiceState();
if (rileyLinkServiceState==null) { if (rileyLinkServiceState == null) {
LOG.error("RileyLink unreachable. RileyLinkServiceState is null."); LOG.error("RileyLink unreachable. RileyLinkServiceState is null.");
return false; return false;
} }
@ -744,13 +745,13 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
ClockDTO clock = MedtronicUtil.getPumpTime(); ClockDTO clock = MedtronicUtil.getPumpTime();
if (clock==null) { // retry if (clock == null) { // retry
medtronicUIComm.executeCommand(MedtronicCommandType.GetRealTimeClock); medtronicUIComm.executeCommand(MedtronicCommandType.GetRealTimeClock);
clock = MedtronicUtil.getPumpTime(); clock = MedtronicUtil.getPumpTime();
} }
if (clock==null) if (clock == null)
return; return;
int timeDiff = Math.abs(clock.timeDifference); int timeDiff = Math.abs(clock.timeDifference);
@ -866,6 +867,11 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
}).start(); }).start();
} }
long now = System.currentTimeMillis();
detailedBolusInfo.date = now;
detailedBolusInfo.deliverAt = now; // not sure about that one
TreatmentsPlugin.getPlugin().addToHistoryTreatment(detailedBolusInfo, true); TreatmentsPlugin.getPlugin().addToHistoryTreatment(detailedBolusInfo, true);
// we subtract insulin, exact amount will be visible with next remainingInsulin update. // we subtract insulin, exact amount will be visible with next remainingInsulin update.
@ -877,7 +883,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
// calculate time for bolus and set driver to busy for that time // calculate time for bolus and set driver to busy for that time
int bolusTime = (int) (detailedBolusInfo.insulin * 42.0d); int bolusTime = (int) (detailedBolusInfo.insulin * 42.0d);
long time = System.currentTimeMillis() + (bolusTime * 1000); long time = now + (bolusTime * 1000);
this.busyTimestamps.add(time); this.busyTimestamps.add(time);
setEnableCustomAction(MedtronicCustomActionType.ClearBolusBlock, true); setEnableCustomAction(MedtronicCustomActionType.ClearBolusBlock, true);
@ -1065,10 +1071,10 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
@Override @Override
public PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes, Profile profile, public PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes, Profile profile,
boolean enforceNew) { boolean enforceNew) {
if (percent==0) { if (percent == 0) {
return setTempBasalAbsolute(0.0d, durationInMinutes, profile, enforceNew); return setTempBasalAbsolute(0.0d, durationInMinutes, profile, enforceNew);
} else { } else {
double absoluteValue = profile.getBasal() * (percent /100.0d); double absoluteValue = profile.getBasal() * (percent / 100.0d);
getMDTPumpStatus(); getMDTPumpStatus();
absoluteValue = pumpStatusLocal.pumpType.determineCorrectBasalSize(absoluteValue); absoluteValue = pumpStatusLocal.pumpType.determineCorrectBasalSize(absoluteValue);
LOG.warn("setTempBasalPercent [MedtronicPumpPlugin] - You are trying to use setTempBasalPercent with percent other then 0% (%d). This will start setTempBasalAbsolute, with calculated value (%.3f). Result might not be 100% correct.", percent, absoluteValue); LOG.warn("setTempBasalPercent [MedtronicPumpPlugin] - You are trying to use setTempBasalPercent with percent other then 0% (%d). This will start setTempBasalAbsolute, with calculated value (%.3f). Result might not be 100% correct.", percent, absoluteValue);

View file

@ -412,25 +412,18 @@ public class MedtronicPumpHistoryDecoder extends MedtronicHistoryDecoder<PumpHis
rate = body[1] * 0.025f; rate = body[1] * 0.025f;
} }
LOG.info("Basal Profile Start: offset={}, rate={}, index={}, body_raw={}", offset, rate, index, //LOG.info("Basal Profile Start: offset={}, rate={}, index={}, body_raw={}", offset, rate, index, body);
body);
if (rate == null) { if (rate == null) {
LOG.warn("Basal Profile Start (ERROR): offset={}, rate={}, index={}, body_raw={}", offset, rate, index, LOG.warn("Basal Profile Start (ERROR): offset={}, rate={}, index={}, body_raw={}", offset, rate, index,
body); body);
return RecordDecodeStatus.Error; return RecordDecodeStatus.Error;
} else { } else {
// writeData(PumpBaseType.Basal, PumpBasalType.ValueChange, getFormattedFloat(rate, 3),
// entry.getATechDate());
entry.addDecodedData("Value", getFormattedFloat(rate, 3)); entry.addDecodedData("Value", getFormattedFloat(rate, 3));
entry.setDisplayableValue(getFormattedFloat(rate, 3)); entry.setDisplayableValue(getFormattedFloat(rate, 3));
return RecordDecodeStatus.OK; return RecordDecodeStatus.OK;
} }
// profileIndex = asUINT8(data[1]);
// offset = asUINT8(data[7]) * 30 * 1000 * 60;
// rate = (double)(asUINT8(data[8])) / 40.0;
} }

View file

@ -10,12 +10,10 @@ import java.util.List;
import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.pump.common.utils.DateTimeUtil; import info.nightscout.androidaps.plugins.pump.common.utils.DateTimeUtil;
/**
* Created by andy on 9/23/18.
*/
/** /**
* History page contains data, sorted from newest to oldest (0=newest..n=oldest) * History page contains data, sorted from newest to oldest (0=newest..n=oldest)
*
* Created by andy on 9/23/18.
*/ */
public class PumpHistoryResult { public class PumpHistoryResult {
@ -29,8 +27,6 @@ public class PumpHistoryResult {
public List<PumpHistoryEntry> validEntries; public List<PumpHistoryEntry> validEntries;
// private Object validValues;
public PumpHistoryResult(PumpHistoryEntry searchEntry, Long targetDate) { public PumpHistoryResult(PumpHistoryEntry searchEntry, Long targetDate) {
if (searchEntry != null) { if (searchEntry != null) {
/* /*
@ -109,9 +105,8 @@ public class PumpHistoryResult {
if (unprocessedEntry.isAfter(this.searchDate)) { if (unprocessedEntry.isAfter(this.searchDate)) {
this.validEntries.add(unprocessedEntry); this.validEntries.add(unprocessedEntry);
} else { } else {
LOG.debug("PE. PumpHistoryResult. Not after.. Unprocessed Entry [year={},entry={}]", // LOG.debug("PE. PumpHistoryResult. Not after.. Unprocessed Entry [year={},entry={}]",
DateTimeUtil.getYear(unprocessedEntry.atechDateTime), unprocessedEntry); // DateTimeUtil.getYear(unprocessedEntry.atechDateTime), unprocessedEntry);
if (DateTimeUtil.getYear(unprocessedEntry.atechDateTime) > 2015) if (DateTimeUtil.getYear(unprocessedEntry.atechDateTime) > 2015)
olderEntries++; olderEntries++;
} }
@ -131,14 +126,6 @@ public class PumpHistoryResult {
} }
private void clearOrPrepareList() {
if (this.validEntries == null)
this.validEntries = new ArrayList<>();
else
this.validEntries.clear();
}
public String toString() { public String toString() {
return "PumpHistoryResult [unprocessed=" + (unprocessedEntries != null ? "" + unprocessedEntries.size() : "0") + // return "PumpHistoryResult [unprocessed=" + (unprocessedEntries != null ? "" + unprocessedEntries.size() : "0") + //
", valid=" + (validEntries != null ? "" + validEntries.size() : "0") + // ", valid=" + (validEntries != null ? "" + validEntries.size() : "0") + //

View file

@ -49,6 +49,7 @@ import info.nightscout.androidaps.plugins.pump.medtronic.driver.MedtronicPumpSta
import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicConst; import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicConst;
import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil; import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil;
import info.nightscout.androidaps.plugins.treatments.Treatment; import info.nightscout.androidaps.plugins.treatments.Treatment;
import info.nightscout.androidaps.plugins.treatments.TreatmentService;
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.SP; import info.nightscout.androidaps.utils.SP;
@ -76,6 +77,7 @@ public class MedtronicHistoryData {
private boolean isInit = false; private boolean isInit = false;
private Gson gson; private Gson gson;
private Gson gsonCore;
private DatabaseHelper databaseHelper = MainApp.getDbHelper(); private DatabaseHelper databaseHelper = MainApp.getDbHelper();
private ClockDTO pumpTime; private ClockDTO pumpTime;
@ -93,10 +95,15 @@ public class MedtronicHistoryData {
public MedtronicHistoryData() { public MedtronicHistoryData() {
this.allHistory = new ArrayList<>(); this.allHistory = new ArrayList<>();
this.gson = MedtronicUtil.gsonInstance; this.gson = MedtronicUtil.gsonInstance;
this.gsonCore = MedtronicUtil.getGsonInstanceCore();
if (this.gson == null) { if (this.gson == null) {
this.gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(); this.gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
} }
if (this.gsonCore == null) {
this.gsonCore = new GsonBuilder().create();
}
} }
@ -596,7 +603,7 @@ public class MedtronicHistoryData {
if (doubleBolusDebug) if (doubleBolusDebug)
LOG.debug("DoubleBolusDebug: List (before filter): {}, FromDb={}", gson.toJson(entryList), LOG.debug("DoubleBolusDebug: List (before filter): {}, FromDb={}", gson.toJson(entryList),
gson.toJson(entriesFromHistory)); gsonCore.toJson(entriesFromHistory));
filterOutAlreadyAddedEntries(entryList, entriesFromHistory); filterOutAlreadyAddedEntries(entryList, entriesFromHistory);
@ -608,7 +615,7 @@ public class MedtronicHistoryData {
if (doubleBolusDebug) if (doubleBolusDebug)
LOG.debug("DoubleBolusDebug: List (after filter): {}, FromDb={}", gson.toJson(entryList), LOG.debug("DoubleBolusDebug: List (after filter): {}, FromDb={}", gson.toJson(entryList),
gson.toJson(entriesFromHistory)); gsonCore.toJson(entriesFromHistory));
if (isCollectionEmpty(entriesFromHistory)) { if (isCollectionEmpty(entriesFromHistory)) {
for (PumpHistoryEntry treatment : entryList) { for (PumpHistoryEntry treatment : entryList) {
@ -861,6 +868,7 @@ public class MedtronicHistoryData {
return; return;
List<DbObjectBase> removeTreatmentsFromHistory = new ArrayList<>(); List<DbObjectBase> removeTreatmentsFromHistory = new ArrayList<>();
List<PumpHistoryEntry> removeTreatmentsFromPH = new ArrayList<>();
for (DbObjectBase treatment : treatmentsFromHistory) { for (DbObjectBase treatment : treatmentsFromHistory) {
@ -878,11 +886,17 @@ public class MedtronicHistoryData {
if (selectedBolus != null) { if (selectedBolus != null) {
entryList.remove(selectedBolus); entryList.remove(selectedBolus);
removeTreatmentsFromPH.add(selectedBolus);
removeTreatmentsFromHistory.add(treatment); removeTreatmentsFromHistory.add(treatment);
} }
} }
} }
if (doubleBolusDebug)
LOG.debug("DoubleBolusDebug: filterOutAlreadyAddedEntries: PumpHistory={}, Treatments={}",
gson.toJson(removeTreatmentsFromPH),
gsonCore.toJson(removeTreatmentsFromHistory));
treatmentsFromHistory.removeAll(removeTreatmentsFromHistory); treatmentsFromHistory.removeAll(removeTreatmentsFromHistory);
} }
@ -946,36 +960,23 @@ public class MedtronicHistoryData {
} else { } else {
DetailedBolusInfo detailedBolusInfo = DetailedBolusInfoStorage.INSTANCE.findDetailedBolusInfo(treatment.date, bolusDTO.getDeliveredAmount()); if (doubleBolusDebug)
LOG.debug("DoubleBolusDebug: addBolus(OldTreatment={}): Bolus={}", treatment, bolusDTO);
treatment.source = Source.PUMP;
treatment.pumpId = bolus.getPumpId();
treatment.insulin = bolusDTO.getDeliveredAmount();
TreatmentService.UpdateReturn updateReturn = TreatmentsPlugin.getPlugin().getService().createOrUpdateMedtronic(treatment, false);
if (doubleBolusDebug) if (doubleBolusDebug)
LOG.debug("DoubleBolusDebug: addBolus(tretament={}): Bolus={}, DetailedBolusInfo={}", treatment, bolusDTO, detailedBolusInfo); LOG.debug("DoubleBolusDebug: addBolus(tretament!=null): NewTreatment={}, UpdateReturn={}", treatment, updateReturn);
if (detailedBolusInfo == null) {
detailedBolusInfo = new DetailedBolusInfo();
if (doubleBolusDebug)
LOG.debug("DoubleBolusDebug: detailedBolusInfoCouldNotBeRetrived !");
}
detailedBolusInfo.date = treatment.date;
detailedBolusInfo.source = Source.PUMP;
detailedBolusInfo.pumpId = bolus.getPumpId();
detailedBolusInfo.insulin = bolusDTO.getDeliveredAmount();
detailedBolusInfo.carbs = treatment.carbs;
addCarbsFromEstimate(detailedBolusInfo, bolus);
if (doubleBolusDebug)
LOG.debug("DoubleBolusDebug: addBolus(tretament!=null): DetailedBolusInfo(New)={}", detailedBolusInfo);
boolean newRecord = TreatmentsPlugin.getPlugin().addToHistoryTreatment(detailedBolusInfo, false);
bolus.setLinkedObject(detailedBolusInfo);
if (isLogEnabled()) if (isLogEnabled())
LOG.debug("editBolus - [date={},pumpId={}, insulin={}, newRecord={}]", detailedBolusInfo.date, LOG.debug("editBolus - [date={},pumpId={}, insulin={}, newRecord={}]", treatment.date,
detailedBolusInfo.pumpId, detailedBolusInfo.insulin, newRecord); treatment.pumpId, treatment.insulin, updateReturn.toString());
bolus.setLinkedObject(treatment);
} }
} }

View file

@ -61,8 +61,7 @@ public class MedtronicUtil extends RileyLinkUtil {
private static int doneBit = 1 << 7; private static int doneBit = 1 << 7;
private static ClockDTO pumpTime; private static ClockDTO pumpTime;
public static Gson gsonInstance = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(); public static Gson gsonInstance = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
public static Gson gsonInstancePretty = new GsonBuilder().excludeFieldsWithoutExposeAnnotation() public static Gson gsonInstanceCore = new GsonBuilder().create();
.setPrettyPrinting().create();
private static BatteryType batteryType = BatteryType.None; private static BatteryType batteryType = BatteryType.None;
@ -70,8 +69,9 @@ public class MedtronicUtil extends RileyLinkUtil {
return gsonInstance; return gsonInstance;
} }
public static Gson getGsonInstancePretty() {
return gsonInstancePretty; public static Gson getGsonInstanceCore() {
return gsonInstanceCore;
} }

View file

@ -17,6 +17,7 @@ import info.nightscout.androidaps.logging.L
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload import info.nightscout.androidaps.plugins.general.nsclient.NSUpload
import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.SP import info.nightscout.androidaps.utils.SP
import info.nightscout.androidaps.utils.T
import org.json.JSONObject import org.json.JSONObject
import org.slf4j.LoggerFactory import org.slf4j.LoggerFactory
@ -51,7 +52,7 @@ object SourceDexcomPlugin : PluginBase(PluginDescription()
} }
fun findDexcomPackageName(): String? { fun findDexcomPackageName(): String? {
val packageManager = MainApp.instance().packageManager; val packageManager = MainApp.instance().packageManager
for (packageInfo in packageManager.getInstalledPackages(0)) { for (packageInfo in packageManager.getInstalledPackages(0)) {
if (PACKAGE_NAMES.contains(packageInfo.packageName)) return packageInfo.packageName if (PACKAGE_NAMES.contains(packageInfo.packageName)) return packageInfo.packageName
} }
@ -64,43 +65,53 @@ object SourceDexcomPlugin : PluginBase(PluginDescription()
val sensorType = intent.getStringExtra("sensorType") ?: "" val sensorType = intent.getStringExtra("sensorType") ?: ""
val glucoseValues = intent.getBundleExtra("glucoseValues") val glucoseValues = intent.getBundleExtra("glucoseValues")
for (i in 0 until glucoseValues.size()) { for (i in 0 until glucoseValues.size()) {
val glucoseValue = glucoseValues.getBundle(i.toString()) glucoseValues.getBundle(i.toString())?.let { glucoseValue ->
val bgReading = BgReading() val bgReading = BgReading()
bgReading.value = glucoseValue!!.getInt("glucoseValue").toDouble() bgReading.value = glucoseValue.getInt("glucoseValue").toDouble()
bgReading.direction = glucoseValue.getString("trendArrow") bgReading.direction = glucoseValue.getString("trendArrow")
bgReading.date = glucoseValue.getLong("timestamp") * 1000 bgReading.date = glucoseValue.getLong("timestamp") * 1000
bgReading.raw = 0.0 bgReading.raw = 0.0
if (MainApp.getDbHelper().createIfNotExists(bgReading, "Dexcom$sensorType")) { if (MainApp.getDbHelper().createIfNotExists(bgReading, "Dexcom$sensorType")) {
if (SP.getBoolean(R.string.key_dexcomg5_nsupload, false)) { if (SP.getBoolean(R.string.key_dexcomg5_nsupload, false)) {
NSUpload.uploadBg(bgReading, "AndroidAPS-Dexcom$sensorType") NSUpload.uploadBg(bgReading, "AndroidAPS-Dexcom$sensorType")
} }
if (SP.getBoolean(R.string.key_dexcomg5_xdripupload, false)) { if (SP.getBoolean(R.string.key_dexcomg5_xdripupload, false)) {
NSUpload.sendToXdrip(bgReading) NSUpload.sendToXdrip(bgReading)
}
} }
} }
} }
val meters = intent.getBundleExtra("meters") val meters = intent.getBundleExtra("meters")
for (i in 0 until meters.size()) { for (i in 0 until meters.size()) {
val meter = meters.getBundle(i.toString()) val meter = meters.getBundle(i.toString())
val timestamp = meter!!.getLong("timestamp") * 1000 meter?.let {
if (MainApp.getDbHelper().getCareportalEventFromTimestamp(timestamp) != null) continue val timestamp = it.getLong("timestamp") * 1000
val jsonObject = JSONObject() val now = DateUtil.now()
jsonObject.put("enteredBy", "AndroidAPS-Dexcom$sensorType") if (timestamp > now - T.months(1).msecs() && timestamp < now)
jsonObject.put("created_at", DateUtil.toISOString(timestamp)) if (MainApp.getDbHelper().getCareportalEventFromTimestamp(timestamp) == null) {
jsonObject.put("eventType", CareportalEvent.BGCHECK) val jsonObject = JSONObject()
jsonObject.put("glucoseType", "Finger") jsonObject.put("enteredBy", "AndroidAPS-Dexcom$sensorType")
jsonObject.put("glucose", meter.getInt("meterValue")) jsonObject.put("created_at", DateUtil.toISOString(timestamp))
jsonObject.put("units", Constants.MGDL) jsonObject.put("eventType", CareportalEvent.BGCHECK)
NSUpload.uploadCareportalEntryToNS(jsonObject) jsonObject.put("glucoseType", "Finger")
jsonObject.put("glucose", meter.getInt("meterValue"))
jsonObject.put("units", Constants.MGDL)
NSUpload.uploadCareportalEntryToNS(jsonObject)
}
}
} }
if (SP.getBoolean(R.string.key_dexcom_lognssensorchange, false) && intent.hasExtra("sensorInsertionTime")) { if (SP.getBoolean(R.string.key_dexcom_lognssensorchange, false) && intent.hasExtra("sensorInsertionTime")) {
val sensorInsertionTime = intent.extras!!.getLong("sensorInsertionTime") * 1000 intent.extras?.let {
if (MainApp.getDbHelper().getCareportalEventFromTimestamp(sensorInsertionTime) == null) { val sensorInsertionTime = it.getLong("sensorInsertionTime") * 1000
val jsonObject = JSONObject() val now = DateUtil.now()
jsonObject.put("enteredBy", "AndroidAPS-Dexcom$sensorType") if (sensorInsertionTime > now - T.months(1).msecs() && sensorInsertionTime < now)
jsonObject.put("created_at", DateUtil.toISOString(sensorInsertionTime)) if (MainApp.getDbHelper().getCareportalEventFromTimestamp(sensorInsertionTime) == null) {
jsonObject.put("eventType", CareportalEvent.SENSORCHANGE) val jsonObject = JSONObject()
NSUpload.uploadCareportalEntryToNS(jsonObject) jsonObject.put("enteredBy", "AndroidAPS-Dexcom$sensorType")
jsonObject.put("created_at", DateUtil.toISOString(sensorInsertionTime))
jsonObject.put("eventType", CareportalEvent.SENSORCHANGE)
NSUpload.uploadCareportalEntryToNS(jsonObject)
}
} }
} }
} catch (e: Exception) { } catch (e: Exception) {

View file

@ -736,6 +736,14 @@ public class TreatmentService extends OrmLiteBaseService<DatabaseHelper> {
boolean newRecord; boolean newRecord;
boolean success; boolean success;
@Override
public String toString() {
return "UpdateReturn [" +
"newRecord=" + newRecord +
", success=" + success +
']';
}
} }
} }

View file

@ -349,7 +349,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
long time = System.currentTimeMillis(); long time = System.currentTimeMillis();
synchronized (treatments) { synchronized (treatments) {
if (MedtronicHistoryData.doubleBolusDebug) if (MedtronicHistoryData.doubleBolusDebug)
log.debug("DoubleBolusDebug: AllTreatmentsInDb: {}", MedtronicUtil.getGsonInstance().toJson(treatments)); log.debug("DoubleBolusDebug: AllTreatmentsInDb: {}", MedtronicUtil.getGsonInstanceCore().toJson(treatments));
for (Treatment t : treatments) { for (Treatment t : treatments) {
if (t.date <= time && t.date >= fromTimestamp) if (t.date <= time && t.date >= fromTimestamp)
@ -357,7 +357,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
} }
if (MedtronicHistoryData.doubleBolusDebug) if (MedtronicHistoryData.doubleBolusDebug)
log.debug("DoubleBolusDebug: FilteredTreatments: AfterTime={}, Items={}", fromTimestamp, MedtronicUtil.getGsonInstance().toJson(in5minback)); log.debug("DoubleBolusDebug: FilteredTreatments: AfterTime={}, Items={}", fromTimestamp, MedtronicUtil.getGsonInstanceCore().toJson(in5minback));
return in5minback; return in5minback;
} }

View file

@ -21,7 +21,7 @@ public class ChargingStateReceiver extends BroadcastReceiver {
lastEvent = event; lastEvent = event;
} }
public EventChargingState grabChargingState(Context context) { public static EventChargingState grabChargingState(Context context) {
BatteryManager bm = (BatteryManager) context.getSystemService(Context.BATTERY_SERVICE); BatteryManager bm = (BatteryManager) context.getSystemService(Context.BATTERY_SERVICE);
if (bm == null) if (bm == null)

View file

@ -26,11 +26,6 @@ public class NetworkChangeReceiver extends BroadcastReceiver {
public static final NetworkChangeReceiver instance = new NetworkChangeReceiver(); public static final NetworkChangeReceiver instance = new NetworkChangeReceiver();
// TODO: Split NSClient into network state component that can be used by several plugins and logic for plugin
public static void fetch() {
new NetworkChangeReceiver().grabNetworkStatus(MainApp.instance().getApplicationContext());
}
@Override @Override
public void onReceive(final Context context, final Intent intent) { public void onReceive(final Context context, final Intent intent) {
EventNetworkChange event = grabNetworkStatus(context); EventNetworkChange event = grabNetworkStatus(context);
@ -39,7 +34,7 @@ public class NetworkChangeReceiver extends BroadcastReceiver {
} }
@Nullable @Nullable
public EventNetworkChange grabNetworkStatus(final Context context) { public static EventNetworkChange grabNetworkStatus(final Context context) {
EventNetworkChange event = new EventNetworkChange(); EventNetworkChange event = new EventNetworkChange();
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

View file

@ -33,9 +33,7 @@ public class NsClientReceiverDelegateTest {
AAPSMocker.mockMainApp(); AAPSMocker.mockMainApp();
AAPSMocker.mockApplicationContext(); AAPSMocker.mockApplicationContext();
Context context = MainApp.instance().getApplicationContext(); sut = new NsClientReceiverDelegate();
sut = new NsClientReceiverDelegate(context);
} }
@Test @Test