allign Insight logging with AAPS

This commit is contained in:
Milos Kozak 2018-09-10 19:28:03 +02:00
parent 90cae60f9b
commit 7070c0a72b
10 changed files with 201 additions and 134 deletions

View file

@ -9,7 +9,6 @@ import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.widget.LinearLayout; import android.widget.LinearLayout;
import com.squareup.otto.Subscribe; import com.squareup.otto.Subscribe;
import org.slf4j.Logger; import org.slf4j.Logger;
@ -18,6 +17,7 @@ import org.slf4j.LoggerFactory;
import java.util.List; import java.util.List;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.Common.SubscriberFragment; import info.nightscout.androidaps.plugins.Common.SubscriberFragment;
import info.nightscout.androidaps.plugins.PumpInsight.events.EventInsightUpdateGui; import info.nightscout.androidaps.plugins.PumpInsight.events.EventInsightUpdateGui;
import info.nightscout.androidaps.plugins.PumpInsight.utils.StatusItem; import info.nightscout.androidaps.plugins.PumpInsight.utils.StatusItem;
@ -26,7 +26,7 @@ import info.nightscout.utils.FabricPrivacy;
public class InsightFragment extends SubscriberFragment { public class InsightFragment extends SubscriberFragment {
private static final Logger log = LoggerFactory.getLogger(InsightFragment.class); private static final Logger log = LoggerFactory.getLogger(L.PUMP);
private static final Handler sLoopHandler = new Handler(); private static final Handler sLoopHandler = new Handler();
private static volatile boolean refresh = false; private static volatile boolean refresh = false;
private static volatile boolean pending = false; private static volatile boolean pending = false;

View file

@ -85,6 +85,7 @@ import static info.nightscout.androidaps.plugins.PumpInsight.history.PumpIdCache
@SuppressWarnings("AccessStaticViaInstance") @SuppressWarnings("AccessStaticViaInstance")
public class InsightPlugin extends PluginBase implements PumpInterface, ConstraintsInterface { public class InsightPlugin extends PluginBase implements PumpInterface, ConstraintsInterface {
private Logger log = LoggerFactory.getLogger(L.PUMP);
private static volatile InsightPlugin plugin; private static volatile InsightPlugin plugin;
@ -100,7 +101,6 @@ public class InsightPlugin extends PluginBase implements PumpInterface, Constrai
private static Integer reservoirInUnits = 0; private static Integer reservoirInUnits = 0;
private static boolean initialized = false; private static boolean initialized = false;
private static volatile boolean update_pending = false; private static volatile boolean update_pending = false;
private static Logger log = LoggerFactory.getLogger(InsightPlugin.class);
private StatusTaskRunner.Result statusResult; private StatusTaskRunner.Result statusResult;
private long statusResultTime = -1; private long statusResultTime = -1;
private long lastDataTime = 0; private long lastDataTime = 0;
@ -120,16 +120,12 @@ public class InsightPlugin extends PluginBase implements PumpInterface, Constrai
.preferencesId(R.xml.pref_insightpump) .preferencesId(R.xml.pref_insightpump)
.description(R.string.description_pump_insight) .description(R.string.description_pump_insight)
); );
log("InsightPlugin instantiated"); if (L.isEnabled(L.PUMP))
log.debug("InsightPlugin instantiated");
pumpDescription.setPumpDescription(PumpType.AccuChekInsight); pumpDescription.setPumpDescription(PumpType.AccuChekInsight);
} }
// just log during debugging
private static void log(String msg) {
android.util.Log.e("INSIGHTPUMP", msg);
}
private static void updateGui() { private static void updateGui() {
update_pending = false; update_pending = false;
MainApp.bus().post(new EventInsightUpdateGui()); MainApp.bus().post(new EventInsightUpdateGui());
@ -144,7 +140,8 @@ public class InsightPlugin extends PluginBase implements PumpInterface, Constrai
if (!connector_enabled) { if (!connector_enabled) {
synchronized (this) { synchronized (this) {
if (!connector_enabled) { if (!connector_enabled) {
log("Instantiating connector"); if (L.isEnabled(L.PUMP))
log.debug("Instantiating connector");
connector_enabled = true; connector_enabled = true;
this.connector = Connector.get(); this.connector = Connector.get();
this.connector.init(); this.connector.init();
@ -158,7 +155,8 @@ public class InsightPlugin extends PluginBase implements PumpInterface, Constrai
if (connector_enabled) { if (connector_enabled) {
synchronized (this) { synchronized (this) {
if (connector_enabled) { if (connector_enabled) {
log("Shutting down connector"); if (L.isEnabled(L.PUMP))
log.debug("Shutting down connector");
Connector.get().shutdown(); Connector.get().shutdown();
connector_enabled = false; connector_enabled = false;
} }
@ -239,18 +237,21 @@ public class InsightPlugin extends PluginBase implements PumpInterface, Constrai
@Override @Override
public void connect(String reason) { public void connect(String reason) {
log("InsightPlugin::connect()"); if (L.isEnabled(L.PUMP))
log.debug("InsightPlugin::connect()");
try { try {
if (!connector.isPumpConnected()) { if (!connector.isPumpConnected()) {
if (Helpers.ratelimit("insight-connect-timer", 40)) { if (Helpers.ratelimit("insight-connect-timer", 40)) {
log("Actually requesting a connect"); if (L.isEnabled(L.PUMP))
log.debug("Actually requesting a connect");
connector.connectToPump(); connector.connectToPump();
} }
} else { } else {
log("Already connected"); if (L.isEnabled(L.PUMP))
log.debug("Already connected");
} }
} catch (NullPointerException e) { } catch (NullPointerException e) {
log("Could not sconnect - null pointer: " + e); log.error("Could not sconnect - null pointer: " + e);
} }
// TODO review // TODO review
@ -260,54 +261,63 @@ public class InsightPlugin extends PluginBase implements PumpInterface, Constrai
@Override @Override
public void disconnect(String reason) { public void disconnect(String reason) {
log("InsightPlugin::disconnect()"); if (L.isEnabled(L.PUMP))
log.debug("InsightPlugin::disconnect()");
try { try {
if (!SP.getBoolean("insight_always_connected", false)) { if (!SP.getBoolean("insight_always_connected", false)) {
log("Requesting disconnect"); if (L.isEnabled(L.PUMP))
log.debug("Requesting disconnect");
connector.disconnectFromPump(); connector.disconnectFromPump();
} else { } else {
log("Not disconnecting due to preference"); if (L.isEnabled(L.PUMP))
log.debug("Not disconnecting due to preference");
} }
} catch (NullPointerException e) { } catch (NullPointerException e) {
log("Could not disconnect - null pointer: " + e); log.error("Could not disconnect - null pointer: " + e);
} }
} }
@Override @Override
public void stopConnecting() { public void stopConnecting() {
log("InsightPlugin::stopConnecting()"); if (L.isEnabled(L.PUMP))
log.debug("InsightPlugin::stopConnecting()");
try { try {
if (isConnecting()) { if (isConnecting()) {
if (!SP.getBoolean("insight_always_connected", false)) { if (!SP.getBoolean("insight_always_connected", false)) {
log("Requesting disconnect"); if (L.isEnabled(L.PUMP))
log.debug("Requesting disconnect");
connector.disconnectFromPump(); connector.disconnectFromPump();
} else { } else {
log("Not disconnecting due to preference"); if (L.isEnabled(L.PUMP))
log.debug("Not disconnecting due to preference");
} }
} else { } else {
log("Not currently trying to connect so not stopping connection"); if (L.isEnabled(L.PUMP))
log.debug("Not currently trying to connect so not stopping connection");
} }
} catch (NullPointerException e) { } catch (NullPointerException e) {
log("Could not stop connecting - null pointer: " + e); log.error("Could not stop connecting - null pointer: " + e);
} }
} }
@Override @Override
public void getPumpStatus() { public void getPumpStatus() {
if (L.isEnabled(L.PUMP))
log("getPumpStatus"); log.debug("getPumpStatus");
if (Connector.get().isPumpConnected()) { if (Connector.get().isPumpConnected()) {
log("is connected.. requesting status"); if (L.isEnabled(L.PUMP))
log.debug("is connected.. requesting status");
try { try {
setStatusResult(fetchTaskRunner(new StatusTaskRunner(connector.getServiceConnector()), StatusTaskRunner.Result.class)); setStatusResult(fetchTaskRunner(new StatusTaskRunner(connector.getServiceConnector()), StatusTaskRunner.Result.class));
log("GOT STATUS RESULT!!! PARTY WOOHOO!!!"); if (L.isEnabled(L.PUMP))
log.debug("GOT STATUS RESULT!!! PARTY WOOHOO!!!");
statusResultTime = Helpers.tsl(); statusResultTime = Helpers.tsl();
processStatusResult(); processStatusResult();
updateGui(); updateGui();
connector.requestHistoryReSync(); connector.requestHistoryReSync();
connector.requestHistorySync(); connector.requestHistorySync();
} catch (Exception e) { } catch (Exception e) {
log("StatusTaskRunner wasn't successful."); log.error("StatusTaskRunner wasn't successful.");
if (connector.getServiceConnector().isConnectedToService() && connector.getServiceConnector().getStatus() != Status.CONNECTED) { if (connector.getServiceConnector().isConnectedToService() && connector.getServiceConnector().getStatus() != Status.CONNECTED) {
if (Helpers.ratelimit("insight-reconnect", 2)) { if (Helpers.ratelimit("insight-reconnect", 2)) {
Connector.connectToPump(); Connector.connectToPump();
@ -316,7 +326,8 @@ public class InsightPlugin extends PluginBase implements PumpInterface, Constrai
} }
} }
} else { } else {
log("not connected.. not requesting status"); if (L.isEnabled(L.PUMP))
log.debug("not connected.. not requesting status");
} }
} }
@ -344,7 +355,8 @@ public class InsightPlugin extends PluginBase implements PumpInterface, Constrai
if (profile.getBasalValues().length > i + 1) if (profile.getBasalValues().length > i + 1)
nextValue = profile.getBasalValues()[i + 1]; nextValue = profile.getBasalValues()[i + 1];
profileBlocks.add(new BRProfileBlock.ProfileBlock((((nextValue != null ? nextValue.timeAsSeconds : 24 * 60 * 60) - basalValue.timeAsSeconds) / 60), Helpers.roundDouble(basalValue.value, 2))); profileBlocks.add(new BRProfileBlock.ProfileBlock((((nextValue != null ? nextValue.timeAsSeconds : 24 * 60 * 60) - basalValue.timeAsSeconds) / 60), Helpers.roundDouble(basalValue.value, 2)));
log("setNewBasalProfile: " + basalValue.value + " for " + Integer.toString(((nextValue != null ? nextValue.timeAsSeconds : 24 * 60 * 60) - basalValue.timeAsSeconds) / 60)); if (L.isEnabled(L.PUMP))
log.debug("setNewBasalProfile: " + basalValue.value + " for " + Integer.toString(((nextValue != null ? nextValue.timeAsSeconds : 24 * 60 * 60) - basalValue.timeAsSeconds) / 60));
} }
try { try {
fetchTaskRunner(new WriteBasalProfileTaskRunner(connector.getServiceConnector(), profileBlocks)); fetchTaskRunner(new WriteBasalProfileTaskRunner(connector.getServiceConnector(), profileBlocks));
@ -373,8 +385,9 @@ public class InsightPlugin extends PluginBase implements PumpInterface, Constrai
Profile.BasalValue nextValue = null; Profile.BasalValue nextValue = null;
if (profile.getBasalValues().length > i + 1) if (profile.getBasalValues().length > i + 1)
nextValue = profile.getBasalValues()[i + 1]; nextValue = profile.getBasalValues()[i + 1];
log("isThisProfileSet - Comparing block: Pump: " + profileBlock.getAmount() + " for " + profileBlock.getDuration() if (L.isEnabled(L.PUMP))
+ " Profile: " + basalValue.value + " for " + Integer.toString(((nextValue != null ? nextValue.timeAsSeconds : 24 * 60 * 60) - basalValue.timeAsSeconds) / 60)); log.debug("isThisProfileSet - Comparing block: Pump: " + profileBlock.getAmount() + " for " + profileBlock.getDuration()
+ " Profile: " + basalValue.value + " for " + Integer.toString(((nextValue != null ? nextValue.timeAsSeconds : 24 * 60 * 60) - basalValue.timeAsSeconds) / 60));
if (profileBlock.getDuration() * 60 != (nextValue != null ? nextValue.timeAsSeconds : 24 * 60 * 60) - basalValue.timeAsSeconds) if (profileBlock.getDuration() * 60 != (nextValue != null ? nextValue.timeAsSeconds : 24 * 60 * 60) - basalValue.timeAsSeconds)
return false; return false;
//Allow a little imprecision due to rounding errors //Allow a little imprecision due to rounding errors
@ -425,7 +438,8 @@ public class InsightPlugin extends PluginBase implements PumpInterface, Constrai
} }
if (result.success) { if (result.success) {
log("Success!"); if (L.isEnabled(L.PUMP))
log.debug("Success!");
Treatment t = new Treatment(); Treatment t = new Treatment();
t.isSMB = detailedBolusInfo.isSMB; t.isSMB = detailedBolusInfo.isSMB;
@ -437,10 +451,11 @@ public class InsightPlugin extends PluginBase implements PumpInterface, Constrai
MainApp.bus().post(bolusingEvent); MainApp.bus().post(bolusingEvent);
TreatmentsPlugin.getPlugin().addToHistoryTreatment(detailedBolusInfo, true); TreatmentsPlugin.getPlugin().addToHistoryTreatment(detailedBolusInfo, true);
} else { } else {
log.debug("Failure to deliver treatment"); if (L.isEnabled(L.PUMP))
log.debug("Failure to deliver treatment");
} }
if (L.isEnabled(L.PUMPCOMM)) if (L.isEnabled(L.PUMP))
log.debug("Delivering treatment insulin: " + detailedBolusInfo.insulin + "U carbs: " + detailedBolusInfo.carbs + "g " + result); log.debug("Delivering treatment insulin: " + detailedBolusInfo.insulin + "U carbs: " + detailedBolusInfo.carbs + "g " + result);
updateGui(); updateGui();
@ -489,25 +504,31 @@ public class InsightPlugin extends PluginBase implements PumpInterface, Constrai
@Override @Override
public PumpEnactResult setTempBasalAbsolute(Double absoluteRate, Integer durationInMinutes, Profile profile, boolean enforceNew) { public PumpEnactResult setTempBasalAbsolute(Double absoluteRate, Integer durationInMinutes, Profile profile, boolean enforceNew) {
log("Set TBR absolute: " + absoluteRate); if (L.isEnabled(L.PUMP))
log.debug("Set TBR absolute: " + absoluteRate);
if (getBaseBasalRate() == 0) { if (getBaseBasalRate() == 0) {
log("Base basal rate appears to be zero!"); if (L.isEnabled(L.PUMP))
log.debug("Base basal rate appears to be zero!");
return pumpEnactFailure(); return pumpEnactFailure();
} }
double percent = 100D / getBaseBasalRate() * absoluteRate; double percent = 100D / getBaseBasalRate() * absoluteRate;
log("Calculated requested rate: " + absoluteRate + " base rate: " + getBaseBasalRate() + " percentage: " + percent + "%"); if (L.isEnabled(L.PUMP))
log.debug("Calculated requested rate: " + absoluteRate + " base rate: " + getBaseBasalRate() + " percentage: " + percent + "%");
try { try {
if (percent > 250) { if (percent > 250) {
log("Calculated rate is above 250%, switching to emulation using extended boluses"); if (L.isEnabled(L.PUMP))
log.debug("Calculated rate is above 250%, switching to emulation using extended boluses");
cancelTempBasal(true); cancelTempBasal(true);
if (!setExtendedBolus((absoluteRate - getBaseBasalRate()) / 60D * ((double) durationInMinutes), durationInMinutes).success) { if (!setExtendedBolus((absoluteRate - getBaseBasalRate()) / 60D * ((double) durationInMinutes), durationInMinutes).success) {
//Fallback to TBR if setting an extended bolus didn't work //Fallback to TBR if setting an extended bolus didn't work
log("Setting an extended bolus didn't work, falling back to normal TBR"); if (L.isEnabled(L.PUMP))
log.debug("Setting an extended bolus didn't work, falling back to normal TBR");
return setTempBasalPercent((int) percent, durationInMinutes, profile, true); return setTempBasalPercent((int) percent, durationInMinutes, profile, true);
} }
return new PumpEnactResult().success(true).enacted(true).absolute(absoluteRate).duration(durationInMinutes); return new PumpEnactResult().success(true).enacted(true).absolute(absoluteRate).duration(durationInMinutes);
} else { } else {
log("Calculated rate is below or equal to 250%, using normal TBRs"); if (L.isEnabled(L.PUMP))
log.debug("Calculated rate is below or equal to 250%, using normal TBRs");
cancelExtendedBolus(); cancelExtendedBolus();
return setTempBasalPercent((int) percent, durationInMinutes, profile, true); return setTempBasalPercent((int) percent, durationInMinutes, profile, true);
} }
@ -519,7 +540,8 @@ public class InsightPlugin extends PluginBase implements PumpInterface, Constrai
@Override @Override
public PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes, Profile profile, boolean enforceNew) { public PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes, Profile profile, boolean enforceNew) {
log("Set TBR %"); if (L.isEnabled(L.PUMP))
log.debug("Set TBR %");
percent = (int) Math.round(((double) percent) / 10d) * 10; percent = (int) Math.round(((double) percent) / 10d) * 10;
if (percent == 100) { if (percent == 100) {
@ -536,7 +558,7 @@ public class InsightPlugin extends PluginBase implements PumpInterface, Constrai
.source(Source.USER); .source(Source.USER);
TreatmentsPlugin.getPlugin().addToHistoryTempBasal(tempBasal); TreatmentsPlugin.getPlugin().addToHistoryTempBasal(tempBasal);
updateGui(); updateGui();
if (L.isEnabled(L.PUMPCOMM)) if (L.isEnabled(L.PUMP))
log.debug("Set temp basal " + percent + "% for " + durationInMinutes + "m"); log.debug("Set temp basal " + percent + "% for " + durationInMinutes + "m");
connector.requestHistorySync(5000); connector.requestHistorySync(5000);
connector.tryToGetPumpStatusAgain(); connector.tryToGetPumpStatusAgain();
@ -549,13 +571,14 @@ public class InsightPlugin extends PluginBase implements PumpInterface, Constrai
@Override @Override
public PumpEnactResult cancelTempBasal(boolean enforceNew) { public PumpEnactResult cancelTempBasal(boolean enforceNew) {
log("Cancel TBR"); if (L.isEnabled(L.PUMP))
log.debug("Cancel TBR");
try { try {
cancelExtendedBolus(); cancelExtendedBolus();
realTBRCancel(); realTBRCancel();
updateGui(); updateGui();
if (L.isEnabled(L.PUMPCOMM)) log.debug("Canceling temp basal"); if (L.isEnabled(L.PUMP)) log.debug("Canceling temp basal");
connector.requestHistorySync(5000); connector.requestHistorySync(5000);
connector.tryToGetPumpStatusAgain(); connector.tryToGetPumpStatusAgain();
return new PumpEnactResult().success(true).enacted(true).isTempCancel(true); return new PumpEnactResult().success(true).enacted(true).isTempCancel(true);
@ -576,7 +599,8 @@ public class InsightPlugin extends PluginBase implements PumpInterface, Constrai
@Override @Override
public PumpEnactResult setExtendedBolus(Double insulin, Integer durationInMinutes) { public PumpEnactResult setExtendedBolus(Double insulin, Integer durationInMinutes) {
log("Set Extended bolus " + insulin + " " + durationInMinutes); if (L.isEnabled(L.PUMP))
log.debug("Set Extended bolus " + insulin + " " + durationInMinutes);
try { try {
ExtendedBolusMessage extendedBolusMessage = new ExtendedBolusMessage(); ExtendedBolusMessage extendedBolusMessage = new ExtendedBolusMessage();
extendedBolusMessage.setAmount(insulin); extendedBolusMessage.setAmount(insulin);
@ -592,7 +616,7 @@ public class InsightPlugin extends PluginBase implements PumpInterface, Constrai
updateGui(); updateGui();
connector.requestHistorySync(30000); connector.requestHistorySync(30000);
connector.tryToGetPumpStatusAgain(); connector.tryToGetPumpStatusAgain();
if (L.isEnabled(L.PUMPCOMM)) if (L.isEnabled(L.PUMP))
log.debug("Setting extended bolus: " + insulin + " mins:" + durationInMinutes); log.debug("Setting extended bolus: " + insulin + " mins:" + durationInMinutes);
return new PumpEnactResult().success(true).enacted(true).duration(durationInMinutes).bolusDelivered(insulin); return new PumpEnactResult().success(true).enacted(true).duration(durationInMinutes).bolusDelivered(insulin);
} catch (Exception e) { } catch (Exception e) {
@ -602,7 +626,8 @@ public class InsightPlugin extends PluginBase implements PumpInterface, Constrai
@Override @Override
public PumpEnactResult cancelExtendedBolus() { public PumpEnactResult cancelExtendedBolus() {
log("Cancel Extended bolus"); if (L.isEnabled(L.PUMP))
log.debug("Cancel Extended bolus");
Integer bolusId = null; Integer bolusId = null;
@ -613,7 +638,7 @@ public class InsightPlugin extends PluginBase implements PumpInterface, Constrai
exStop.source = Source.USER; exStop.source = Source.USER;
TreatmentsPlugin.getPlugin().addToHistoryExtendedBolus(exStop); TreatmentsPlugin.getPlugin().addToHistoryExtendedBolus(exStop);
} }
if (L.isEnabled(L.PUMPCOMM)) log.debug("Cancel extended bolus:"); if (L.isEnabled(L.PUMP)) log.debug("Cancel extended bolus:");
if (bolusId != null) connector.requestHistorySync(5000); if (bolusId != null) connector.requestHistorySync(5000);
connector.tryToGetPumpStatusAgain(); connector.tryToGetPumpStatusAgain();
updateGui(); updateGui();
@ -625,7 +650,8 @@ public class InsightPlugin extends PluginBase implements PumpInterface, Constrai
private int deliverBolus(double bolusValue) throws Exception { private int deliverBolus(double bolusValue) throws Exception {
log("DeliverBolus: " + bolusValue); if (L.isEnabled(L.PUMP))
log.debug("DeliverBolus: " + bolusValue);
final StandardBolusMessage message = new StandardBolusMessage(); final StandardBolusMessage message = new StandardBolusMessage();
message.setAmount(bolusValue); message.setAmount(bolusValue);
@ -637,7 +663,8 @@ public class InsightPlugin extends PluginBase implements PumpInterface, Constrai
public JSONObject getJSONStatus(Profile profile, String profileName) { public JSONObject getJSONStatus(Profile profile, String profileName) {
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
if (Helpers.msSince(connector.getLastContactTime()) > (60 * 60 * 1000)) { if (Helpers.msSince(connector.getLastContactTime()) > (60 * 60 * 1000)) {
log("getJSONStatus not returning as data likely stale"); if (L.isEnabled(L.PUMP))
log.debug("getJSONStatus not returning as data likely stale");
return null; return null;
} }
@ -841,7 +868,7 @@ public class InsightPlugin extends PluginBase implements PumpInterface, Constrai
break; break;
default: default:
log("ERROR: unknown bolus type! " + activeBolus.getBolusType()); log.error("ERROR: unknown bolus type! " + activeBolus.getBolusType());
} }
} }
@ -859,7 +886,7 @@ public class InsightPlugin extends PluginBase implements PumpInterface, Constrai
lastDataTime = System.currentTimeMillis(); lastDataTime = System.currentTimeMillis();
return result; return result;
} catch (Exception e) { } catch (Exception e) {
log("Error while fetching " + taskRunner.getClass().getSimpleName() + ": " + e.getClass().getSimpleName()); log.error("Error while fetching " + taskRunner.getClass().getSimpleName() + ": " + e.getClass().getSimpleName());
throw e; throw e;
} }
} }
@ -870,7 +897,7 @@ public class InsightPlugin extends PluginBase implements PumpInterface, Constrai
lastDataTime = System.currentTimeMillis(); lastDataTime = System.currentTimeMillis();
return result; return result;
} catch (Exception e) { } catch (Exception e) {
log("Error while fetching " + message.getClass().getSimpleName() + ": " + e.getClass().getSimpleName()); log.error("Error while fetching " + message.getClass().getSimpleName() + ": " + e.getClass().getSimpleName());
throw e; throw e;
} }
} }

View file

@ -5,6 +5,9 @@ import android.os.PowerManager;
import com.squareup.otto.Subscribe; import com.squareup.otto.Subscribe;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Formatter; import java.util.Formatter;
import java.util.HashMap; import java.util.HashMap;
@ -14,6 +17,7 @@ import java.util.Map;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.events.EventFeatureRunning; import info.nightscout.androidaps.events.EventFeatureRunning;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.PumpInsight.events.EventInsightUpdateGui; import info.nightscout.androidaps.plugins.PumpInsight.events.EventInsightUpdateGui;
import info.nightscout.androidaps.plugins.PumpInsight.history.HistoryReceiver; import info.nightscout.androidaps.plugins.PumpInsight.history.HistoryReceiver;
import info.nightscout.androidaps.plugins.PumpInsight.history.LiveHistory; import info.nightscout.androidaps.plugins.PumpInsight.history.LiveHistory;
@ -31,16 +35,16 @@ import static sugar.free.sightparser.handling.SightService.COMPATIBILITY_VERSION
/** /**
* Created by jamorham on 23/01/2018. * Created by jamorham on 23/01/2018.
* * <p>
* Connects to SightRemote app service using SightParser library * Connects to SightRemote app service using SightParser library
* * <p>
* SightRemote and SightParser created by Tebbe Ubben * SightRemote and SightParser created by Tebbe Ubben
* * <p>
* Original proof of concept SightProxy by jamorham * Original proof of concept SightProxy by jamorham
*
*/ */
public class Connector { public class Connector {
private static Logger log = LoggerFactory.getLogger(L.PUMP);
// TODO connection statistics // TODO connection statistics
@ -65,7 +69,8 @@ public class Connector {
public synchronized void onStatusChange(Status status, long statusTime, long waitTime) { public synchronized void onStatusChange(Status status, long statusTime, long waitTime) {
if ((status != lastStatus) || (Helpers.msSince(lastStatusTime) > 2000)) { if ((status != lastStatus) || (Helpers.msSince(lastStatusTime) > 2000)) {
log("Status change: " + status); if (L.isEnabled(L.PUMP))
log.debug("Status change: " + status);
updateStatusStatistics(lastStatus, lastStatusTime); updateStatusStatistics(lastStatus, lastStatusTime);
lastStatus = status; lastStatus = status;
@ -78,7 +83,8 @@ public class Connector {
MainApp.bus().post(new EventInsightUpdateGui()); MainApp.bus().post(new EventInsightUpdateGui());
} else { } else {
log("Same status as before: " + status); if (L.isEnabled(L.PUMP))
log.debug("Same status as before: " + status);
} }
} }
@ -87,29 +93,32 @@ public class Connector {
@Override @Override
public synchronized void onServiceConnected() { public synchronized void onServiceConnected() {
log("On service connected"); if (L.isEnabled(L.PUMP))
log.debug("On service connected");
try { try {
final String remoteVersion = serviceConnector.getRemoteVersion(); final String remoteVersion = serviceConnector.getRemoteVersion();
if (remoteVersion.equals(COMPATIBILITY_VERSION)) { if (remoteVersion.equals(COMPATIBILITY_VERSION)) {
serviceConnector.connect(); serviceConnector.connect();
} else { } else {
log("PROTOCOL VERSION MISMATCH! local: " + COMPATIBILITY_VERSION + " remote: " + remoteVersion); log.error("PROTOCOL VERSION MISMATCH! local: " + COMPATIBILITY_VERSION + " remote: " + remoteVersion);
statusCallback.onStatusChange(Status.INCOMPATIBLE, 0, 0); statusCallback.onStatusChange(Status.INCOMPATIBLE, 0, 0);
compatabilityMessage = MainApp.gs(R.string.insight_incompatible_compantion_app_we_need_version) + " " + getLocalVersion(); compatabilityMessage = MainApp.gs(R.string.insight_incompatible_compantion_app_we_need_version) + " " + getLocalVersion();
serviceConnector.disconnectFromService(); serviceConnector.disconnectFromService();
} }
} catch (NullPointerException e) { } catch (NullPointerException e) {
log("ERROR: null pointer when trying to connect to pump"); log.error("ERROR: null pointer when trying to connect to pump");
} }
statusCallback.onStatusChange(safeGetStatus(), 0, 0); statusCallback.onStatusChange(safeGetStatus(), 0, 0);
} }
@Override @Override
public synchronized void onServiceDisconnected() { public synchronized void onServiceDisconnected() {
log("Disconnected from service"); if (L.isEnabled(L.PUMP))
log.debug("Disconnected from service");
if (Helpers.ratelimit("insight-automatic-reconnect", 30)) { if (Helpers.ratelimit("insight-automatic-reconnect", 30)) {
log("Scheduling automatic service reconnection"); if (L.isEnabled(L.PUMP))
log.debug("Scheduling automatic service reconnection");
Helpers.runOnUiThreadDelayed(new Runnable() { Helpers.runOnUiThreadDelayed(new Runnable() {
@Override @Override
public void run() { public void run() {
@ -147,11 +156,13 @@ public class Connector {
} }
public synchronized static void connectToPump(long keep_alive) { public synchronized static void connectToPump(long keep_alive) {
log("Attempting to connect to pump."); if (L.isEnabled(L.PUMP))
log.debug("Attempting to connect to pump.");
if (keep_alive > 0 && Helpers.tsl() + keep_alive > stayConnectedTill) { if (keep_alive > 0 && Helpers.tsl() + keep_alive > stayConnectedTill) {
stayConnectedTime = keep_alive; stayConnectedTime = keep_alive;
stayConnectedTill = Helpers.tsl() + keep_alive; stayConnectedTill = Helpers.tsl() + keep_alive;
log("Staying connected till: " + Helpers.dateTimeText(stayConnectedTill)); if (L.isEnabled(L.PUMP))
log.debug("Staying connected till: " + Helpers.dateTimeText(stayConnectedTill));
delayedDisconnectionThread(); delayedDisconnectionThread();
} }
get().getServiceConnector().connect(); get().getServiceConnector().connect();
@ -159,18 +170,16 @@ public class Connector {
public static void disconnectFromPump() { public static void disconnectFromPump() {
if (Helpers.tsl() >= stayConnectedTill) { if (Helpers.tsl() >= stayConnectedTill) {
log("Requesting real pump disconnect"); if (L.isEnabled(L.PUMP))
log.debug("Requesting real pump disconnect");
get().getServiceConnector().disconnect(); get().getServiceConnector().disconnect();
} else { } else {
log("Cannot disconnect as due to keep alive till: " + Helpers.dateTimeText(stayConnectedTill)); if (L.isEnabled(L.PUMP))
log.debug("Cannot disconnect as due to keep alive till: " + Helpers.dateTimeText(stayConnectedTill));
// TODO set a disconnection timer? // TODO set a disconnection timer?
} }
} }
static void log(String msg) {
android.util.Log.e("INSIGHTPUMP", msg);
}
static String getLocalVersion() { static String getLocalVersion() {
return COMPATIBILITY_VERSION; return COMPATIBILITY_VERSION;
} }
@ -206,7 +215,8 @@ public class Connector {
if (keepAliveActive()) { if (keepAliveActive()) {
if (Helpers.ratelimit("extend-insight-keepalive", 10)) { if (Helpers.ratelimit("extend-insight-keepalive", 10)) {
stayConnectedTill = Helpers.tsl() + stayConnectedTime; stayConnectedTill = Helpers.tsl() + stayConnectedTime;
log("Keep-alive extended until: " + Helpers.dateTimeText(stayConnectedTill)); if (L.isEnabled(L.PUMP))
log.debug("Keep-alive extended until: " + Helpers.dateTimeText(stayConnectedTill));
} }
} }
} }
@ -236,7 +246,8 @@ public class Connector {
try { try {
while (disconnect_thread_running && keepAliveActive()) { while (disconnect_thread_running && keepAliveActive()) {
if (Helpers.ratelimit("insight-expiry-notice", 5)) { if (Helpers.ratelimit("insight-expiry-notice", 5)) {
log("Staying connected thread expires: " + Helpers.dateTimeText(stayConnectedTill)); if (L.isEnabled(L.PUMP))
log.debug("Staying connected thread expires: " + Helpers.dateTimeText(stayConnectedTill));
} }
try { try {
Thread.sleep(1000); Thread.sleep(1000);
@ -246,10 +257,12 @@ public class Connector {
} }
if (disconnect_thread_running) { if (disconnect_thread_running) {
log("Sending the real delayed disconnect"); if (L.isEnabled(L.PUMP))
log.debug("Sending the real delayed disconnect");
get().getServiceConnector().disconnect(); get().getServiceConnector().disconnect();
} else { } else {
log("Disconnect thread already terminating"); if (L.isEnabled(L.PUMP))
log.debug("Disconnect thread already terminating");
} }
} finally { } finally {
Helpers.releaseWakeLock(wl); Helpers.releaseWakeLock(wl);
@ -258,7 +271,8 @@ public class Connector {
} }
}).start(); }).start();
} else { } else {
log("Disconnect thread already running"); if (L.isEnabled(L.PUMP))
log.debug("Disconnect thread already running");
} }
} }
} }
@ -269,7 +283,8 @@ public class Connector {
public synchronized void shutdown() { public synchronized void shutdown() {
if (instance != null) { if (instance != null) {
log("Attempting to shut down connector"); if (L.isEnabled(L.PUMP))
log.debug("Attempting to shut down connector");
try { try {
disconnect_thread_running = false; disconnect_thread_running = false;
try { try {
@ -285,17 +300,17 @@ public class Connector {
try { try {
instance.serviceConnector.disconnect(); instance.serviceConnector.disconnect();
} catch (Exception e) { } catch (Exception e) {
log("Exception disconnecting: " + e); log.error("Exception disconnecting: " + e);
} }
try { try {
instance.serviceConnector.disconnectFromService(); instance.serviceConnector.disconnectFromService();
} catch (Exception e) { } catch (Exception e) {
log("Excpetion disconnecting service: " + e); log.error("Excpetion disconnecting service: " + e);
} }
instance.serviceConnector = null; instance.serviceConnector = null;
instance = null; instance = null;
} catch (Exception e) { } catch (Exception e) {
log("Exception shutting down: " + e); log.error("Exception shutting down: " + e);
} }
} }
} }
@ -309,7 +324,8 @@ public class Connector {
} }
public synchronized void init() { public synchronized void init() {
log("Connector::init()"); if (L.isEnabled(L.PUMP))
log.debug("Connector::init()");
if (serviceConnector == null) { if (serviceConnector == null) {
companionAppInstalled = isCompanionAppInstalled(); companionAppInstalled = isCompanionAppInstalled();
if (companionAppInstalled) { if (companionAppInstalled) {
@ -318,9 +334,11 @@ public class Connector {
serviceConnector.addStatusCallback(statusCallback); serviceConnector.addStatusCallback(statusCallback);
serviceConnector.setConnectionCallback(connectionCallback); serviceConnector.setConnectionCallback(connectionCallback);
serviceConnector.connectToService(); serviceConnector.connectToService();
log("Trying to connect"); if (L.isEnabled(L.PUMP))
log.debug("Trying to connect");
} else { } else {
log("Not trying init due to missing companion app"); if (L.isEnabled(L.PUMP))
log.debug("Not trying init due to missing companion app");
} }
} else { } else {
if (!serviceConnector.isConnectedToService()) { if (!serviceConnector.isConnectedToService()) {
@ -328,7 +346,8 @@ public class Connector {
serviceConnector = null; serviceConnector = null;
init(); init();
} else { } else {
log("Trying to reconnect to service (" + serviceReconnects + ")"); if (L.isEnabled(L.PUMP))
log.debug("Trying to reconnect to service (" + serviceReconnects + ")");
serviceConnector.connectToService(); serviceConnector.connectToService();
serviceReconnects++; serviceReconnects++;
} }
@ -384,7 +403,8 @@ public class Connector {
} }
if (!isConnected()) { if (!isConnected()) {
log("Not connected to companion"); if (L.isEnabled(L.PUMP))
log.debug("Not connected to companion");
if (Helpers.ratelimit("insight-app-not-connected", 5)) { if (Helpers.ratelimit("insight-app-not-connected", 5)) {
init(); init();
} }
@ -499,7 +519,8 @@ public class Connector {
Long total = statistics.get(last); Long total = statistics.get(last);
if (total == null) total = 0L; if (total == null) total = 0L;
statistics.put(last, total + Helpers.msSince(since)); statistics.put(last, total + Helpers.msSince(since));
log("Updated statistics for: " + last + " total: " + Helpers.niceTimeScalar(statistics.get(last))); if (L.isEnabled(L.PUMP))
log.debug("Updated statistics for: " + last + " total: " + Helpers.niceTimeScalar(statistics.get(last)));
// TODO persist data // TODO persist data
} }
} }
@ -534,11 +555,13 @@ public class Connector {
if (SP.getBoolean("insight_preemptive_connect", true)) { if (SP.getBoolean("insight_preemptive_connect", true)) {
switch (ev.getFeature()) { switch (ev.getFeature()) {
case WIZARD: case WIZARD:
log("Wizard feature detected, preconnecting to pump"); if (L.isEnabled(L.PUMP))
log.debug("Wizard feature detected, preconnecting to pump");
connectToPump(120 * 1000); connectToPump(120 * 1000);
break; break;
case MAIN: case MAIN:
log("Main feature detected, preconnecting to pump"); if (L.isEnabled(L.PUMP))
log.debug("Main feature detected, preconnecting to pump");
connectToPump(30 * 1000); connectToPump(30 * 1000);
break; break;
} }

View file

@ -12,7 +12,6 @@ public class EventInsightCallback extends Event {
public UUID request_uuid; public UUID request_uuid;
public boolean success = false; public boolean success = false;
public String message = null; public String message = null;
public int response_id = -1;
public Object response_object = null; public Object response_object = null;
public EventInsightCallback() { public EventInsightCallback() {

View file

@ -1,15 +1,22 @@
package info.nightscout.androidaps.plugins.PumpInsight.history; package info.nightscout.androidaps.plugins.PumpInsight.history;
import android.content.Intent; import android.content.Intent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.db.CareportalEvent; import info.nightscout.androidaps.db.CareportalEvent;
import info.nightscout.androidaps.db.TDD; import info.nightscout.androidaps.db.TDD;
import info.nightscout.androidaps.logging.L;
import info.nightscout.utils.DateUtil; import info.nightscout.utils.DateUtil;
import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload; import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload;
import info.nightscout.utils.SP; import info.nightscout.utils.SP;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import sugar.free.sightparser.handling.HistoryBroadcast; import sugar.free.sightparser.handling.HistoryBroadcast;
import java.util.Date; import java.util.Date;
@ -23,6 +30,7 @@ import static info.nightscout.androidaps.plugins.PumpInsight.history.PumpIdCache
*/ */
class HistoryIntentAdapter { class HistoryIntentAdapter {
private Logger log = LoggerFactory.getLogger(L.PUMP);
private HistoryLogAdapter logAdapter = new HistoryLogAdapter(); private HistoryLogAdapter logAdapter = new HistoryLogAdapter();
@ -30,10 +38,6 @@ class HistoryIntentAdapter {
return (Date) intent.getSerializableExtra(name); return (Date) intent.getSerializableExtra(name);
} }
private static void log(String msg) {
android.util.Log.e("HistoryIntentAdapter", msg);
}
static long getRecordUniqueID(long pump_serial_number, long pump_record_id) { static long getRecordUniqueID(long pump_serial_number, long pump_record_id) {
updatePumpSerialNumber(pump_serial_number); updatePumpSerialNumber(pump_serial_number);
return (pump_serial_number * 10000000) + pump_record_id; return (pump_serial_number * 10000000) + pump_record_id;
@ -52,13 +56,14 @@ class HistoryIntentAdapter {
final Date start_time = getDateExtra(intent, HistoryBroadcast.EXTRA_START_TIME); final Date start_time = getDateExtra(intent, HistoryBroadcast.EXTRA_START_TIME);
if ((pump_tbr_duration == -1) || (pump_tbr_percent == -1) || (pump_record_id == -1)) { if ((pump_tbr_duration == -1) || (pump_tbr_percent == -1) || (pump_record_id == -1)) {
log("Invalid TBR record!!!"); log.error("Invalid TBR record!!!");
return; return;
} }
final long record_unique_id = getRecordUniqueID(pump_serial_number, pump_record_id); final long record_unique_id = getRecordUniqueID(pump_serial_number, pump_record_id);
log("Creating TBR record: " + pump_tbr_percent + "% " + pump_tbr_duration + "m" + " id:" + record_unique_id); if (L.isEnabled(L.PUMP))
log.debug("Creating TBR record: " + pump_tbr_percent + "% " + pump_tbr_duration + "m" + " id:" + record_unique_id);
logAdapter.createTBRrecord(start_time, pump_tbr_percent, pump_tbr_duration, record_unique_id); logAdapter.createTBRrecord(start_time, pump_tbr_percent, pump_tbr_duration, record_unique_id);
} }
@ -82,7 +87,7 @@ class HistoryIntentAdapter {
switch (bolus_type) { switch (bolus_type) {
case "STANDARD": case "STANDARD":
if (immediate_amount == -1) { if (immediate_amount == -1) {
log("ERROR Standard bolus fails sanity check"); log.error("ERROR Standard bolus fails sanity check");
return; return;
} }
LiveHistory.setStatus(bolus_type + " BOLUS\n" + immediate_amount + "U ", event_time.getTime()); LiveHistory.setStatus(bolus_type + " BOLUS\n" + immediate_amount + "U ", event_time.getTime());
@ -91,7 +96,7 @@ class HistoryIntentAdapter {
case "EXTENDED": case "EXTENDED":
if ((extended_insulin == -1) || (extended_minutes == -1)) { if ((extended_insulin == -1) || (extended_minutes == -1)) {
log("ERROR: Extended bolus fails sanity check"); log.error("ERROR: Extended bolus fails sanity check");
return; return;
} }
LiveHistory.setStatus(bolus_type + " BOLUS\n" + extended_insulin + "U over " + extended_minutes + " min, ", event_time.getTime()); LiveHistory.setStatus(bolus_type + " BOLUS\n" + extended_insulin + "U over " + extended_minutes + " min, ", event_time.getTime());
@ -100,7 +105,7 @@ class HistoryIntentAdapter {
case "MULTIWAVE": case "MULTIWAVE":
if ((immediate_amount == -1) || (extended_insulin == -1) || (extended_minutes == -1)) { if ((immediate_amount == -1) || (extended_insulin == -1) || (extended_minutes == -1)) {
log("ERROR: Multiwave bolus fails sanity check"); log.error("ERROR: Multiwave bolus fails sanity check");
return; return;
} }
LiveHistory.setStatus(bolus_type + " BOLUS\n" + immediate_amount + "U + " + extended_insulin + "U over " + extended_minutes + " min, ", event_time.getTime()); LiveHistory.setStatus(bolus_type + " BOLUS\n" + immediate_amount + "U + " + extended_insulin + "U over " + extended_minutes + " min, ", event_time.getTime());
@ -108,7 +113,7 @@ class HistoryIntentAdapter {
logAdapter.createExtendedBolusRecord(start_time, extended_insulin, extended_minutes, record_unique_id); logAdapter.createExtendedBolusRecord(start_time, extended_insulin, extended_minutes, record_unique_id);
break; break;
default: default:
log("ERROR, UNKNWON BOLUS TYPE: " + bolus_type); log.error("ERROR, UNKNWON BOLUS TYPE: " + bolus_type);
} }
} }
@ -137,7 +142,8 @@ class HistoryIntentAdapter {
private void uploadCareportalEvent(Date date, String event) { private void uploadCareportalEvent(Date date, String event) {
if (SP.getBoolean("insight_automatic_careportal_events", false)) { if (SP.getBoolean("insight_automatic_careportal_events", false)) {
if (MainApp.getDbHelper().getCareportalEventFromTimestamp(date.getTime()) != null) return; if (MainApp.getDbHelper().getCareportalEventFromTimestamp(date.getTime()) != null)
return;
try { try {
JSONObject data = new JSONObject(); JSONObject data = new JSONObject();
String enteredBy = SP.getString("careportal_enteredby", ""); String enteredBy = SP.getString("careportal_enteredby", "");
@ -157,7 +163,8 @@ class HistoryIntentAdapter {
String alertType = intent.getStringExtra(HistoryBroadcast.EXTRA_ALERT_TYPE); String alertType = intent.getStringExtra(HistoryBroadcast.EXTRA_ALERT_TYPE);
int alertText = getAlertText(alertType); int alertText = getAlertText(alertType);
if (alertText == 0) return; if (alertText == 0) return;
if (MainApp.getDbHelper().getCareportalEventFromTimestamp(date.getTime()) != null) return; if (MainApp.getDbHelper().getCareportalEventFromTimestamp(date.getTime()) != null)
return;
logNote(date, MainApp.gs(alertText)); logNote(date, MainApp.gs(alertText));
} }
} }
@ -195,7 +202,8 @@ class HistoryIntentAdapter {
private void logNote(Date date, String note) { private void logNote(Date date, String note) {
try { try {
if (MainApp.getDbHelper().getCareportalEventFromTimestamp(date.getTime()) != null) return; if (MainApp.getDbHelper().getCareportalEventFromTimestamp(date.getTime()) != null)
return;
JSONObject data = new JSONObject(); JSONObject data = new JSONObject();
String enteredBy = SP.getString("careportal_enteredby", ""); String enteredBy = SP.getString("careportal_enteredby", "");
if (!enteredBy.equals("")) data.put("enteredBy", enteredBy); if (!enteredBy.equals("")) data.put("enteredBy", enteredBy);

View file

@ -1,5 +1,8 @@
package info.nightscout.androidaps.plugins.PumpInsight.history; package info.nightscout.androidaps.plugins.PumpInsight.history;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date; import java.util.Date;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
@ -7,6 +10,7 @@ import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.db.ExtendedBolus; import info.nightscout.androidaps.db.ExtendedBolus;
import info.nightscout.androidaps.db.Source; import info.nightscout.androidaps.db.Source;
import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin; import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin;
/** /**
@ -16,13 +20,10 @@ import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin;
*/ */
class HistoryLogAdapter { class HistoryLogAdapter {
private Logger log = LoggerFactory.getLogger(L.PUMP);
private static final long MAX_TIME_DIFFERENCE = 61000; private static final long MAX_TIME_DIFFERENCE = 61000;
private static void log(String msg) {
android.util.Log.e("HISTORYLOG", msg);
}
void createTBRrecord(Date eventDate, int percent, int duration, long record_id) { void createTBRrecord(Date eventDate, int percent, int duration, long record_id) {
TemporaryBasal temporaryBasal = new TemporaryBasal().date(eventDate.getTime()); TemporaryBasal temporaryBasal = new TemporaryBasal().date(eventDate.getTime());
@ -30,23 +31,29 @@ class HistoryLogAdapter {
final TemporaryBasal temporaryBasalFromHistory = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(eventDate.getTime()); final TemporaryBasal temporaryBasalFromHistory = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(eventDate.getTime());
if (temporaryBasalFromHistory == null) { if (temporaryBasalFromHistory == null) {
log("Create new TBR: " + eventDate + " " + percent + " " + duration); if (L.isEnabled(L.PUMP))
log.debug("Create new TBR: " + eventDate + " " + percent + " " + duration);
} else { } else {
log("Loaded existing TBR record: " + temporaryBasalFromHistory.toString()); if (L.isEnabled(L.PUMP))
log.debug("Loaded existing TBR record: " + temporaryBasalFromHistory.toString());
if (Math.abs(eventDate.getTime() - temporaryBasalFromHistory.date) < MAX_TIME_DIFFERENCE) { if (Math.abs(eventDate.getTime() - temporaryBasalFromHistory.date) < MAX_TIME_DIFFERENCE) {
if (temporaryBasalFromHistory.source != Source.PUMP) { if (temporaryBasalFromHistory.source != Source.PUMP) {
if (temporaryBasalFromHistory.percentRate == percent) { if (temporaryBasalFromHistory.percentRate == percent) {
log("Things seem to match: %" + percent); if (L.isEnabled(L.PUMP))
log.debug("Things seem to match: %" + percent);
temporaryBasal = temporaryBasalFromHistory; temporaryBasal = temporaryBasalFromHistory;
MainApp.getDbHelper().delete(temporaryBasalFromHistory); MainApp.getDbHelper().delete(temporaryBasalFromHistory);
} else { } else {
log("This record has different percent rates: " + temporaryBasalFromHistory.percentRate + " vs us: " + percent); if (L.isEnabled(L.PUMP))
log.debug("This record has different percent rates: " + temporaryBasalFromHistory.percentRate + " vs us: " + percent);
} }
} else { } else {
log("This record is already a pump record!"); if (L.isEnabled(L.PUMP))
log.debug("This record is already a pump record!");
} }
} else { } else {
log("Time difference too great! : " + (eventDate.getTime() - temporaryBasalFromHistory.date)); if (L.isEnabled(L.PUMP))
log.debug("Time difference too great! : " + (eventDate.getTime() - temporaryBasalFromHistory.date));
} }
} }

View file

@ -54,10 +54,6 @@ public class HistoryReceiver {
// History // History
private static void log(String msg) {
android.util.Log.e("INSIGHTPUMPHR", msg);
}
public static String getStatusString() { public static String getStatusString() {
return status.toString(); return status.toString();
} }

View file

@ -1,5 +1,9 @@
package info.nightscout.androidaps.plugins.PumpInsight.history; package info.nightscout.androidaps.plugins.PumpInsight.history;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.logging.L;
import info.nightscout.utils.SP; import info.nightscout.utils.SP;
/** /**
@ -7,18 +11,16 @@ import info.nightscout.utils.SP;
*/ */
public class PumpIdCache { public class PumpIdCache {
private static Logger log = LoggerFactory.getLogger(L.PUMP);
private static final String INSIGHT_PUMP_ID_PREF = "insight-pump-id"; private static final String INSIGHT_PUMP_ID_PREF = "insight-pump-id";
private static long cachedPumpSerialNumber = -1; private static long cachedPumpSerialNumber = -1;
private static void log(String msg) {
android.util.Log.e("PumpIdCache", msg);
}
static void updatePumpSerialNumber(long pump_serial_number) { static void updatePumpSerialNumber(long pump_serial_number) {
if (pump_serial_number != cachedPumpSerialNumber) { if (pump_serial_number != cachedPumpSerialNumber) {
cachedPumpSerialNumber = pump_serial_number; cachedPumpSerialNumber = pump_serial_number;
log("Updating pump serial number: " + pump_serial_number); if (L.isEnabled(L.PUMP))
log.debug("Updating pump serial number: " + pump_serial_number);
SP.putLong(INSIGHT_PUMP_ID_PREF, cachedPumpSerialNumber); SP.putLong(INSIGHT_PUMP_ID_PREF, cachedPumpSerialNumber);
} }
} }

View file

@ -7,6 +7,9 @@ import android.os.Handler;
import android.os.PowerManager; import android.os.PowerManager;
import android.util.Log; import android.util.Log;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.math.RoundingMode; import java.math.RoundingMode;
import java.text.DecimalFormat; import java.text.DecimalFormat;
@ -16,17 +19,17 @@ import java.util.Map;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.logging.L;
/** /**
* Created by jamorham on 24/01/2018. * Created by jamorham on 24/01/2018.
* * <p>
* Useful utility methods from xDrip+ * Useful utility methods from xDrip+
*
*/ */
public class Helpers { public class Helpers {
private static Logger log = LoggerFactory.getLogger(L.PUMP);
private static final String TAG = "InsightHelpers";
private static final Map<String, Long> rateLimits = new HashMap<>(); private static final Map<String, Long> rateLimits = new HashMap<>();
// singletons to avoid repeated allocation // singletons to avoid repeated allocation
@ -37,7 +40,8 @@ public class Helpers {
public static synchronized boolean ratelimit(String name, int seconds) { public static synchronized boolean ratelimit(String name, int seconds) {
// check if over limit // check if over limit
if ((rateLimits.containsKey(name)) && (tsl() - rateLimits.get(name) < (seconds * 1000))) { if ((rateLimits.containsKey(name)) && (tsl() - rateLimits.get(name) < (seconds * 1000))) {
Log.d(TAG, name + " rate limited: " + seconds + " seconds"); if (L.isEnabled(L.PUMP))
log.debug(name + " rate limited: " + seconds + " seconds");
return false; return false;
} }
// not over limit // not over limit
@ -65,7 +69,7 @@ public class Helpers {
} catch (PackageManager.NameNotFoundException e) { } catch (PackageManager.NameNotFoundException e) {
return false; return false;
} catch (Exception e) { } catch (Exception e) {
Log.wtf(TAG, "Exception trying to determine packages! " + e); log.error("Exception trying to determine packages! " + e);
return false; return false;
} }
} }
@ -160,7 +164,7 @@ public class Helpers {
public static String niceTimeScalarBrief(long t) { public static String niceTimeScalarBrief(long t) {
// TODO i18n wont work for non-latin characterset // TODO i18n wont work for non-latin characterset
return niceTimeScalar(t).replaceFirst("([a-z])[a-z]*", "$1").replace(" ",""); return niceTimeScalar(t).replaceFirst("([a-z])[a-z]*", "$1").replace(" ", "");
} }
public static String hourMinuteString(long timestamp) { public static String hourMinuteString(long timestamp) {

View file

@ -41,11 +41,12 @@ import info.nightscout.utils.SP;
* Created by mike on 05.08.2016. * Created by mike on 05.08.2016.
*/ */
public class VirtualPumpPlugin extends PluginBase implements PumpInterface { public class VirtualPumpPlugin extends PluginBase implements PumpInterface {
static Integer batteryPercent = 50; private Logger log = LoggerFactory.getLogger(L.PUMP);
static Integer reservoirInUnits = 50;
private static Logger log = LoggerFactory.getLogger(VirtualPumpPlugin.class); Integer batteryPercent = 50;
Integer reservoirInUnits = 50;
private static VirtualPumpPlugin plugin = null; private static VirtualPumpPlugin plugin = null;
private static boolean fromNSAreCommingFakedExtendedBoluses = false; private boolean fromNSAreCommingFakedExtendedBoluses = false;
private PumpType pumpType = null; private PumpType pumpType = null;
private long lastDataTime = 0; private long lastDataTime = 0;
private PumpDescription pumpDescription = new PumpDescription(); private PumpDescription pumpDescription = new PumpDescription();