Merge branch 'dev' into insihgtfix

This commit is contained in:
Milos Kozak 2018-08-22 15:47:32 +02:00
commit 45321f889a
124 changed files with 1805 additions and 1806 deletions

View file

@ -62,7 +62,7 @@ android {
targetSdkVersion 25 targetSdkVersion 25
multiDexEnabled true multiDexEnabled true
versionCode 1500 versionCode 1500
version "2.0c-dev" version "2.0e-dev"
buildConfigField "String", "VERSION", '"' + version + '"' buildConfigField "String", "VERSION", '"' + version + '"'
buildConfigField "String", "BUILDVERSION", generateGitBuild() buildConfigField "String", "BUILDVERSION", generateGitBuild()
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

View file

@ -18,7 +18,7 @@
<maxHistory>120</maxHistory> <maxHistory>120</maxHistory>
</rollingPolicy> </rollingPolicy>
<encoder> <encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level [%class{0}.%M\(\):%line]: %msg%n</pattern> <pattern>%d{HH:mm:ss.SSS} [%thread] %.-1level/%logger: [%class{0}.%M\(\):%line]: %msg%n</pattern>
</encoder> </encoder>
</appender> </appender>

View file

@ -57,6 +57,7 @@ public class DetailedBolusInfo {
@Override @Override
public String toString() { public String toString() {
return new Date(date).toLocaleString() + return new Date(date).toLocaleString() +
" date: " + date +
" insulin: " + insulin + " insulin: " + insulin +
" carbs: " + carbs + " carbs: " + carbs +
" isValid: " + isValid + " isValid: " + isValid +

View file

@ -162,6 +162,16 @@ public class BgReading implements DataPointWithLabelInterface {
_id = other._id; _id = other._id;
} }
public BgReading date(long date) {
this.date = date;
return this;
}
public BgReading value(double value) {
this.value = value;
return this;
}
// ------------------ DataPointWithLabelInterface ------------------ // ------------------ DataPointWithLabelInterface ------------------
@Override @Override
public double getX() { public double getX() {

View file

@ -74,7 +74,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
public static final String DATABASE_PROFILESWITCHES = "ProfileSwitches"; public static final String DATABASE_PROFILESWITCHES = "ProfileSwitches";
public static final String DATABASE_TDDS = "TDDs"; public static final String DATABASE_TDDS = "TDDs";
private static final int DATABASE_VERSION = 8; private static final int DATABASE_VERSION = 9;
public static Long earliestDataChange = null; public static Long earliestDataChange = null;
@ -133,6 +133,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
if (oldVersion == 7 && newVersion == 8) { if (oldVersion == 7 && newVersion == 8) {
log.debug("Upgrading database from v7 to v8"); log.debug("Upgrading database from v7 to v8");
} else if (oldVersion == 8 && newVersion == 9) {
log.debug("Upgrading database from v8 to v9");
} else { } else {
log.info(DatabaseHelper.class.getName(), "onUpgrade"); log.info(DatabaseHelper.class.getName(), "onUpgrade");
TableUtils.dropTable(connectionSource, TempTarget.class, true); TableUtils.dropTable(connectionSource, TempTarget.class, true);
@ -317,7 +319,11 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
} }
public static long roundDateToSec(long date) { public static long roundDateToSec(long date) {
return date - date % 1000; long rounded = date - date % 1000;
if (rounded != date)
if (L.isEnabled(L.DATABASE))
log.debug("Rounding " + date + " to " + rounded);
return rounded;
} }
// ------------------- BgReading handling ----------------------- // ------------------- BgReading handling -----------------------

View file

@ -10,9 +10,10 @@ import info.nightscout.androidaps.R;
public class EventPumpStatusChanged extends Event { public class EventPumpStatusChanged extends Event {
public static final int CONNECTING = 0; public static final int CONNECTING = 0;
public static final int CONNECTED = 1; public static final int CONNECTED = 1;
public static final int PERFORMING = 2; public static final int HANDSHAKING = 2;
public static final int DISCONNECTING = 3; public static final int PERFORMING = 3;
public static final int DISCONNECTED = 4; public static final int DISCONNECTING = 4;
public static final int DISCONNECTED = 5;
public int sStatus = DISCONNECTED; public int sStatus = DISCONNECTED;
public int sSecondsElapsed = 0; public int sSecondsElapsed = 0;
@ -47,6 +48,8 @@ public class EventPumpStatusChanged extends Event {
public String textStatus() { public String textStatus() {
if (sStatus == CONNECTING) if (sStatus == CONNECTING)
return String.format(MainApp.gs(R.string.danar_history_connectingfor), sSecondsElapsed); return String.format(MainApp.gs(R.string.danar_history_connectingfor), sSecondsElapsed);
else if (sStatus == HANDSHAKING)
return MainApp.gs(R.string.handshaking);
else if (sStatus == CONNECTED) else if (sStatus == CONNECTED)
return MainApp.gs(R.string.connected); return MainApp.gs(R.string.connected);
else if (sStatus == PERFORMING) else if (sStatus == PERFORMING)

View file

@ -1,7 +1,5 @@
package info.nightscout.androidaps.interfaces; package info.nightscout.androidaps.interfaces;
import java.util.Date;
import info.nightscout.androidaps.plugins.Loop.APSResult; import info.nightscout.androidaps.plugins.Loop.APSResult;
/** /**
@ -9,7 +7,7 @@ import info.nightscout.androidaps.plugins.Loop.APSResult;
*/ */
public interface APSInterface { public interface APSInterface {
public APSResult getLastAPSResult(); public APSResult getLastAPSResult();
public Date getLastAPSRun(); public long getLastAPSRun();
public void invoke(String initiator, boolean tempBasalFallback); public void invoke(String initiator, boolean tempBasalFallback);
} }

View file

@ -2,8 +2,6 @@ package info.nightscout.androidaps.interfaces;
import org.json.JSONObject; import org.json.JSONObject;
import java.util.Date;
import info.nightscout.androidaps.data.DetailedBolusInfo; import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.data.PumpEnactResult; import info.nightscout.androidaps.data.PumpEnactResult;
@ -13,11 +11,13 @@ import info.nightscout.androidaps.data.PumpEnactResult;
*/ */
public interface PumpInterface { public interface PumpInterface {
boolean isInitialized(); boolean isInitialized(); // true if pump status has been read and is ready to accept commands
boolean isSuspended(); boolean isSuspended(); // true if suspended (not delivering insulin)
boolean isBusy(); boolean isBusy(); // if true pump is not ready to accept commands right now
boolean isConnected(); boolean isConnected(); // true if BT connection is established
boolean isConnecting(); boolean isConnecting(); // true if BT connection is in progress
boolean isHandshakeInProgress(); // true if BT is connected but initial handshake is still in progress
void finishHandshaking(); // set initial handshake completed
void connect(String reason); void connect(String reason);
void disconnect(String reason); void disconnect(String reason);
@ -29,7 +29,7 @@ public interface PumpInterface {
PumpEnactResult setNewBasalProfile(Profile profile); PumpEnactResult setNewBasalProfile(Profile profile);
boolean isThisProfileSet(Profile profile); boolean isThisProfileSet(Profile profile);
Date lastDataTime(); long lastDataTime();
double getBaseBasalRate(); // base basal rate, not temp basal double getBaseBasalRate(); // base basal rate, not temp basal

View file

@ -99,7 +99,7 @@ public class L {
private static void initialize() { private static void initialize() {
logElements = new ArrayList<>(); logElements = new ArrayList<>();
logElements.add(new LogElement(APS, true)); logElements.add(new LogElement(APS, true));
logElements.add(new LogElement(AUTOSENS, false)); logElements.add(new LogElement(AUTOSENS, true));
logElements.add(new LogElement(BGSOURCE, true)); logElements.add(new LogElement(BGSOURCE, true));
logElements.add(new LogElement(CONFIGBUILDER, true)); logElements.add(new LogElement(CONFIGBUILDER, true));
logElements.add(new LogElement(CORE, true)); logElements.add(new LogElement(CORE, true));

View file

@ -100,7 +100,7 @@ public class CareportalFragment extends SubscriberFragment implements View.OnCli
noProfileView = view.findViewById(R.id.profileview_noprofile); noProfileView = view.findViewById(R.id.profileview_noprofile);
butonsLayout = (LinearLayout) view.findViewById(R.id.careportal_buttons); butonsLayout = (LinearLayout) view.findViewById(R.id.careportal_buttons);
ProfileStore profileStore = MainApp.getConfigBuilder().getActiveProfileInterface().getProfile(); ProfileStore profileStore = MainApp.getConfigBuilder().getActiveProfileInterface() != null ? MainApp.getConfigBuilder().getActiveProfileInterface().getProfile() : null;
if (profileStore == null) { if (profileStore == null) {
noProfileView.setVisibility(View.VISIBLE); noProfileView.setVisibility(View.VISIBLE);
butonsLayout.setVisibility(View.GONE); butonsLayout.setVisibility(View.GONE);

View file

@ -33,21 +33,12 @@ public class DetailedBolusInfoStorage {
log.debug("Existing bolus info: " + store.get(i)); log.debug("Existing bolus info: " + store.get(i));
if (bolustime > infoTime - 60 * 1000 && bolustime < infoTime + 60 * 1000) { if (bolustime > infoTime - 60 * 1000 && bolustime < infoTime + 60 * 1000) {
found = store.get(i); found = store.get(i);
if (L.isEnabled(L.PUMP))
log.debug("Using & removing bolus info: " + store.get(i));
store.remove(i);
break; break;
} }
} }
return found; return found;
} }
public static synchronized void remove(long bolustime) {
for (int i = 0; i < store.size(); i++) {
long infoTime = store.get(i).date;
if (bolustime > infoTime - 60 * 1000 && bolustime < infoTime + 60 * 1000) {
if (L.isEnabled(L.PUMP))
log.debug("Removing bolus info: " + store.get(i));
store.remove(i);
break;
}
}
}
} }

View file

@ -121,13 +121,9 @@ public class FoodService extends OrmLiteBaseService<DatabaseHelper> {
} }
public void onUpgrade(ConnectionSource connectionSource, int oldVersion, int newVersion) { public void onUpgrade(ConnectionSource connectionSource, int oldVersion, int newVersion) {
if (oldVersion == 7 && newVersion == 8) { if (L.isEnabled(L.DATAFOOD))
log.debug("Upgrading database from v7 to v8"); log.info("onUpgrade");
} else {
if (L.isEnabled(L.DATAFOOD))
log.info("onUpgrade");
// this.resetFood(); // this.resetFood();
}
} }
public void onDowngrade(ConnectionSource connectionSource, int oldVersion, int newVersion) { public void onDowngrade(ConnectionSource connectionSource, int oldVersion, int newVersion) {

View file

@ -12,7 +12,6 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date;
import java.util.List; import java.util.List;
import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.Constants;
@ -103,39 +102,15 @@ public class IobCobCalculatorPlugin extends PluginBase {
return bgReadings; return bgReadings;
} }
public void setBgReadings(List<BgReading> bgReadings) {
this.bgReadings = bgReadings;
}
public List<BgReading> getBucketedData() { public List<BgReading> getBucketedData() {
return bucketed_data; return bucketed_data;
} }
@Nullable // roundup to whole minute
public List<BgReading> getBucketedData(long fromTime) {
//log.debug("Locking getBucketedData");
synchronized (dataLock) {
if (bucketed_data == null) {
if (L.isEnabled(L.AUTOSENS))
log.debug("No bucketed data available");
return null;
}
int index = indexNewerThan(fromTime);
if (index > -1) {
List<BgReading> part = bucketed_data.subList(0, index);
if (L.isEnabled(L.AUTOSENS))
log.debug("Bucketed data striped off: " + part.size() + "/" + bucketed_data.size());
return part;
}
}
//log.debug("Releasing getBucketedData");
return null;
}
private int indexNewerThan(long time) {
for (int index = 0; index < bucketed_data.size(); index++) {
if (bucketed_data.get(index).date < time)
return index - 1;
}
return -1;
}
public static long roundUpTime(long time) { public static long roundUpTime(long time) {
if (time % 60000 == 0) if (time % 60000 == 0)
return time; return time;
@ -150,7 +125,7 @@ public class IobCobCalculatorPlugin extends PluginBase {
log.debug("BG data loaded. Size: " + bgReadings.size() + " Start date: " + DateUtil.dateAndTimeString(start) + " End date: " + DateUtil.dateAndTimeString(now)); log.debug("BG data loaded. Size: " + bgReadings.size() + " Start date: " + DateUtil.dateAndTimeString(start) + " End date: " + DateUtil.dateAndTimeString(now));
} }
private boolean isAbout5minData() { public boolean isAbout5minData() {
synchronized (dataLock) { synchronized (dataLock) {
if (bgReadings == null || bgReadings.size() < 3) { if (bgReadings == null || bgReadings.size() < 3) {
return true; return true;
@ -161,10 +136,10 @@ public class IobCobCalculatorPlugin extends PluginBase {
long lastbgTime = bgReadings.get(i - 1).date; long lastbgTime = bgReadings.get(i - 1).date;
long diff = lastbgTime - bgTime; long diff = lastbgTime - bgTime;
totalDiff += diff; totalDiff += diff;
if (diff > 30 * 1000 && diff < 270 * 1000) { // 0:30 - 4:30 if (diff > T.secs(30).msecs() && diff < T.secs(270).msecs()) { // 0:30 - 4:30
log.debug("Interval detection: values: " + bgReadings.size() + " diff: " + (diff / 1000) + "sec is5minData: " + false);
if (L.isEnabled(L.AUTOSENS)) if (L.isEnabled(L.AUTOSENS))
return false; log.debug("Interval detection: values: " + bgReadings.size() + " diff: " + (diff / 1000) + "sec is5minData: " + false);
return false;
} }
} }
double intervals = totalDiff / (5 * 60 * 1000d); double intervals = totalDiff / (5 * 60 * 1000d);
@ -176,7 +151,7 @@ public class IobCobCalculatorPlugin extends PluginBase {
} }
} }
void createBucketedData() { public void createBucketedData() {
if (isAbout5minData()) if (isAbout5minData())
createBucketedData5min(); createBucketedData5min();
else else
@ -184,24 +159,26 @@ public class IobCobCalculatorPlugin extends PluginBase {
} }
@Nullable @Nullable
private BgReading findNewer(long time) { public BgReading findNewer(long time) {
BgReading lastFound = bgReadings.get(0); BgReading lastFound = bgReadings.get(0);
if (lastFound.date < time) return null; if (lastFound.date < time) return null;
for (int i = 1; i < bgReadings.size(); ++i) { for (int i = 1; i < bgReadings.size(); ++i) {
if (bgReadings.get(i).date == time) return bgReadings.get(i);
if (bgReadings.get(i).date > time) continue; if (bgReadings.get(i).date > time) continue;
lastFound = bgReadings.get(i); lastFound = bgReadings.get(i-1);
if (bgReadings.get(i).date < time) break; if (bgReadings.get(i).date < time) break;
} }
return lastFound; return lastFound;
} }
@Nullable @Nullable
private BgReading findOlder(long time) { public BgReading findOlder(long time) {
BgReading lastFound = bgReadings.get(bgReadings.size() - 1); BgReading lastFound = bgReadings.get(bgReadings.size() - 1);
if (lastFound.date > time) return null; if (lastFound.date > time) return null;
for (int i = bgReadings.size() - 2; i >= 0; --i) { for (int i = bgReadings.size() - 2; i >= 0; --i) {
if (bgReadings.get(i).date == time) return bgReadings.get(i);
if (bgReadings.get(i).date < time) continue; if (bgReadings.get(i).date < time) continue;
lastFound = bgReadings.get(i); lastFound = bgReadings.get(i + 1);
if (bgReadings.get(i).date > time) break; if (bgReadings.get(i).date > time) break;
} }
return lastFound; return lastFound;
@ -214,7 +191,7 @@ public class IobCobCalculatorPlugin extends PluginBase {
} }
bucketed_data = new ArrayList<>(); bucketed_data = new ArrayList<>();
long currentTime = bgReadings.get(0).date + 5 * 60 * 1000 - bgReadings.get(0).date % (5 * 60 * 1000) - 5 * 60 * 1000L; long currentTime = bgReadings.get(0).date - bgReadings.get(0).date % T.mins(5).msecs();
//log.debug("First reading: " + new Date(currentTime).toLocaleString()); //log.debug("First reading: " + new Date(currentTime).toLocaleString());
while (true) { while (true) {
@ -224,16 +201,20 @@ public class IobCobCalculatorPlugin extends PluginBase {
if (newer == null || older == null) if (newer == null || older == null)
break; break;
double bgDelta = newer.value - older.value; if (older.date == newer.date) { // direct hit
long timeDiffToNew = newer.date - currentTime; bucketed_data.add(newer);
} else {
double bgDelta = newer.value - older.value;
long timeDiffToNew = newer.date - currentTime;
double currentBg = newer.value - (double) timeDiffToNew / (newer.date - older.date) * bgDelta; double currentBg = newer.value - (double) timeDiffToNew / (newer.date - older.date) * bgDelta;
BgReading newBgreading = new BgReading(); BgReading newBgreading = new BgReading();
newBgreading.date = currentTime; newBgreading.date = currentTime;
newBgreading.value = Math.round(currentBg); newBgreading.value = Math.round(currentBg);
bucketed_data.add(newBgreading); bucketed_data.add(newBgreading);
//log.debug("BG: " + newBgreading.value + " (" + new Date(newBgreading.date).toLocaleString() + ") Prev: " + older.value + " (" + new Date(older.date).toLocaleString() + ") Newer: " + newer.value + " (" + new Date(newer.date).toLocaleString() + ")"); //log.debug("BG: " + newBgreading.value + " (" + new Date(newBgreading.date).toLocaleString() + ") Prev: " + older.value + " (" + new Date(older.date).toLocaleString() + ") Newer: " + newer.value + " (" + new Date(newer.date).toLocaleString() + ")");
currentTime -= 5 * 60 * 1000L; }
currentTime -= T.mins(5).msecs();
} }
} }
@ -300,9 +281,9 @@ public class IobCobCalculatorPlugin extends PluginBase {
} }
// Normalize bucketed data // Normalize bucketed data
for (int i = bucketed_data.size() - 2; i > 0 ; i--) { for (int i = bucketed_data.size() - 2; i > 0; i--) {
BgReading current = bucketed_data.get(i); BgReading current = bucketed_data.get(i);
BgReading previous = bucketed_data.get(i+1); BgReading previous = bucketed_data.get(i + 1);
long msecDiff = current.date - previous.date; long msecDiff = current.date - previous.date;
long adjusted = (msecDiff - T.mins(5).msecs()) / 1000; long adjusted = (msecDiff - T.mins(5).msecs()) / 1000;
log.debug("Adjusting bucketed data time. Current: " + DateUtil.toISOString(current.date) + " to: " + DateUtil.toISOString(previous.date + T.mins(5).msecs()) + " by " + adjusted + " sec"); log.debug("Adjusting bucketed data time. Current: " + DateUtil.toISOString(current.date) + " to: " + DateUtil.toISOString(previous.date + T.mins(5).msecs()) + " by " + adjusted + " sec");
@ -324,7 +305,7 @@ public class IobCobCalculatorPlugin extends PluginBase {
getBGDataFrom = Math.max(oldestDataAvailable, (long) (from - T.hours(1).msecs() * (24 + dia))); getBGDataFrom = Math.max(oldestDataAvailable, (long) (from - T.hours(1).msecs() * (24 + dia)));
if (getBGDataFrom == oldestDataAvailable) if (getBGDataFrom == oldestDataAvailable)
if (L.isEnabled(L.AUTOSENS)) if (L.isEnabled(L.AUTOSENS))
log.debug("Limiting data to oldest available temps: " + new Date(oldestDataAvailable).toString()); log.debug("Limiting data to oldest available temps: " + DateUtil.dateAndTimeFullString(oldestDataAvailable));
} else } else
getBGDataFrom = (long) (from - T.hours(1).msecs() * (24 + dia)); getBGDataFrom = (long) (from - T.hours(1).msecs() * (24 + dia));
return getBGDataFrom; return getBGDataFrom;
@ -370,11 +351,11 @@ public class IobCobCalculatorPlugin extends PluginBase {
} }
@Nullable @Nullable
private Long findPreviousTimeFromBucketedData(long time) { public Long findPreviousTimeFromBucketedData(long time) {
if (bucketed_data == null) if (bucketed_data == null)
return null; return null;
for (int index = 0; index < bucketed_data.size(); index++) { for (int index = 0; index < bucketed_data.size(); index++) {
if (bucketed_data.get(index).date < time) if (bucketed_data.get(index).date <= time)
return bucketed_data.get(index).date; return bucketed_data.get(index).date;
} }
return null; return null;
@ -685,11 +666,11 @@ public class IobCobCalculatorPlugin extends PluginBase {
// clear up 5 min back for proper COB calculation // clear up 5 min back for proper COB calculation
long time = ev.time - 5 * 60 * 1000L; long time = ev.time - 5 * 60 * 1000L;
if (L.isEnabled(L.AUTOSENS)) if (L.isEnabled(L.AUTOSENS))
log.debug("Invalidating cached data to: " + new Date(time).toLocaleString()); log.debug("Invalidating cached data to: " + DateUtil.dateAndTimeFullString(time));
for (int index = iobTable.size() - 1; index >= 0; index--) { for (int index = iobTable.size() - 1; index >= 0; index--) {
if (iobTable.keyAt(index) > time) { if (iobTable.keyAt(index) > time) {
if (L.isEnabled(L.AUTOSENS)) if (L.isEnabled(L.AUTOSENS))
log.debug("Removing from iobTable: " + new Date(iobTable.keyAt(index)).toLocaleString()); log.debug("Removing from iobTable: " + DateUtil.dateAndTimeFullString(iobTable.keyAt(index)));
iobTable.removeAt(index); iobTable.removeAt(index);
} else { } else {
break; break;
@ -698,7 +679,7 @@ public class IobCobCalculatorPlugin extends PluginBase {
for (int index = autosensDataTable.size() - 1; index >= 0; index--) { for (int index = autosensDataTable.size() - 1; index >= 0; index--) {
if (autosensDataTable.keyAt(index) > time) { if (autosensDataTable.keyAt(index) > time) {
if (L.isEnabled(L.AUTOSENS)) if (L.isEnabled(L.AUTOSENS))
log.debug("Removing from autosensDataTable: " + new Date(autosensDataTable.keyAt(index)).toLocaleString()); log.debug("Removing from autosensDataTable: " + DateUtil.dateAndTimeFullString(autosensDataTable.keyAt(index)));
autosensDataTable.removeAt(index); autosensDataTable.removeAt(index);
} else { } else {
break; break;
@ -707,7 +688,7 @@ public class IobCobCalculatorPlugin extends PluginBase {
for (int index = basalDataTable.size() - 1; index >= 0; index--) { for (int index = basalDataTable.size() - 1; index >= 0; index--) {
if (basalDataTable.keyAt(index) > time) { if (basalDataTable.keyAt(index) > time) {
if (L.isEnabled(L.AUTOSENS)) if (L.isEnabled(L.AUTOSENS))
log.debug("Removing from basalDataTable: " + new Date(basalDataTable.keyAt(index)).toLocaleString()); log.debug("Removing from basalDataTable: " + DateUtil.dateAndTimeFullString(basalDataTable.keyAt(index)));
basalDataTable.removeAt(index); basalDataTable.removeAt(index);
} else { } else {
break; break;

View file

@ -180,11 +180,17 @@ public class IobCobOref1Thread extends Thread {
if (hourAgoData != null) { if (hourAgoData != null) {
int initialIndex = autosensDataTable.indexOfKey(hourAgoData.time); int initialIndex = autosensDataTable.indexOfKey(hourAgoData.time);
if (L.isEnabled(L.AUTOSENS)) if (L.isEnabled(L.AUTOSENS))
log.debug(">>>>> bucketed_data.size()=" + bucketed_data.size() + " i=" + i + "hourAgoData=" + hourAgoData.toString()); log.debug(">>>>> bucketed_data.size()=" + bucketed_data.size() + " i=" + i + " hourAgoData=" + hourAgoData.toString());
int past = 1; int past = 1;
try { // try {
for (; past < 12; past++) { for (; past < 12; past++) {
AutosensData ad = autosensDataTable.valueAt(initialIndex + past); AutosensData ad = autosensDataTable.valueAt(initialIndex + past);
if (L.isEnabled(L.AUTOSENS)) {
log.debug(">>>>> past=" + past + " ad=" + (ad != null ? ad.toString() : null));
if (ad == null)
autosensDataTable.toString();
}
// let it here crash on NPE to get more data as i cannot reproduce this bug
double deviationSlope = (ad.avgDeviation - avgDeviation) / (ad.time - bgTime) * 1000 * 60 * 5; double deviationSlope = (ad.avgDeviation - avgDeviation) / (ad.time - bgTime) * 1000 * 60 * 5;
if (ad.avgDeviation > maxDeviation) { if (ad.avgDeviation > maxDeviation) {
slopeFromMaxDeviation = Math.min(0, deviationSlope); slopeFromMaxDeviation = Math.min(0, deviationSlope);
@ -198,17 +204,20 @@ public class IobCobOref1Thread extends Thread {
//if (Config.isEnabled(L.AUTOSENS)) //if (Config.isEnabled(L.AUTOSENS))
// log.debug("Deviations: " + new Date(bgTime) + new Date(ad.time) + " avgDeviation=" + avgDeviation + " deviationSlope=" + deviationSlope + " slopeFromMaxDeviation=" + slopeFromMaxDeviation + " slopeFromMinDeviation=" + slopeFromMinDeviation); // log.debug("Deviations: " + new Date(bgTime) + new Date(ad.time) + " avgDeviation=" + avgDeviation + " deviationSlope=" + deviationSlope + " slopeFromMaxDeviation=" + slopeFromMaxDeviation + " slopeFromMinDeviation=" + slopeFromMinDeviation);
} }
} catch (Exception e) { // } catch (Exception e) {
log.error("Unhandled exception", e); // log.error("Unhandled exception", e);
FabricPrivacy.logException(e); // FabricPrivacy.logException(e);
FabricPrivacy.getInstance().logCustom(new CustomEvent("CatchedError") // FabricPrivacy.getInstance().logCustom(new CustomEvent("CatchedError")
.putCustomAttribute("buildversion", BuildConfig.BUILDVERSION) // .putCustomAttribute("buildversion", BuildConfig.BUILDVERSION)
.putCustomAttribute("version", BuildConfig.VERSION) // .putCustomAttribute("version", BuildConfig.VERSION)
.putCustomAttribute("autosensDataTable", iobCobCalculatorPlugin.getAutosensDataTable().toString()) // .putCustomAttribute("autosensDataTable", iobCobCalculatorPlugin.getAutosensDataTable().toString())
.putCustomAttribute("for_data", ">>>>> bucketed_data.size()=" + bucketed_data.size() + " i=" + i + "hourAgoData=" + hourAgoData.toString()) // .putCustomAttribute("for_data", ">>>>> bucketed_data.size()=" + bucketed_data.size() + " i=" + i + "hourAgoData=" + hourAgoData.toString())
.putCustomAttribute("past", past) // .putCustomAttribute("past", past)
); // );
} // }
} else {
if (L.isEnabled(L.AUTOSENS))
log.debug(">>>>> bucketed_data.size()=" + bucketed_data.size() + " i=" + i + " hourAgoData=" + "null");
} }
} }

View file

@ -179,11 +179,17 @@ public class IobCobThread extends Thread {
if (hourAgoData != null) { if (hourAgoData != null) {
int initialIndex = autosensDataTable.indexOfKey(hourAgoData.time); int initialIndex = autosensDataTable.indexOfKey(hourAgoData.time);
if (L.isEnabled(L.AUTOSENS)) if (L.isEnabled(L.AUTOSENS))
log.debug(">>>>> bucketed_data.size()=" + bucketed_data.size() + " i=" + i + "hourAgoData=" + hourAgoData.toString()); log.debug(">>>>> bucketed_data.size()=" + bucketed_data.size() + " i=" + i + " hourAgoData=" + hourAgoData.toString());
int past = 1; int past = 1;
try { // try {
for (; past < 12; past++) { for (; past < 12; past++) {
AutosensData ad = autosensDataTable.valueAt(initialIndex + past); AutosensData ad = autosensDataTable.valueAt(initialIndex + past);
if (L.isEnabled(L.AUTOSENS)) {
log.debug(">>>>> past=" + past + " ad=" + (ad != null ? ad.toString() : null));
if (ad == null)
autosensDataTable.toString();
}
// let it here crash on NPE to get more data as i cannot reproduce this bug
double deviationSlope = (ad.avgDeviation - avgDeviation) / (ad.time - bgTime) * 1000 * 60 * 5; double deviationSlope = (ad.avgDeviation - avgDeviation) / (ad.time - bgTime) * 1000 * 60 * 5;
if (ad.avgDeviation > maxDeviation) { if (ad.avgDeviation > maxDeviation) {
slopeFromMaxDeviation = Math.min(0, deviationSlope); slopeFromMaxDeviation = Math.min(0, deviationSlope);
@ -197,17 +203,20 @@ public class IobCobThread extends Thread {
//if (Config.isEnabled(L.AUTOSENS)) //if (Config.isEnabled(L.AUTOSENS))
// log.debug("Deviations: " + new Date(bgTime) + new Date(ad.time) + " avgDeviation=" + avgDeviation + " deviationSlope=" + deviationSlope + " slopeFromMaxDeviation=" + slopeFromMaxDeviation + " slopeFromMinDeviation=" + slopeFromMinDeviation); // log.debug("Deviations: " + new Date(bgTime) + new Date(ad.time) + " avgDeviation=" + avgDeviation + " deviationSlope=" + deviationSlope + " slopeFromMaxDeviation=" + slopeFromMaxDeviation + " slopeFromMinDeviation=" + slopeFromMinDeviation);
} }
} catch (Exception e) { // } catch (Exception e) {
log.error("Unhandled exception", e); // log.error("Unhandled exception", e);
FabricPrivacy.logException(e); // FabricPrivacy.logException(e);
FabricPrivacy.getInstance().logCustom(new CustomEvent("CatchedError") // FabricPrivacy.getInstance().logCustom(new CustomEvent("CatchedError")
.putCustomAttribute("buildversion", BuildConfig.BUILDVERSION) // .putCustomAttribute("buildversion", BuildConfig.BUILDVERSION)
.putCustomAttribute("version", BuildConfig.VERSION) // .putCustomAttribute("version", BuildConfig.VERSION)
.putCustomAttribute("autosensDataTable", iobCobCalculatorPlugin.getAutosensDataTable().toString()) // .putCustomAttribute("autosensDataTable", iobCobCalculatorPlugin.getAutosensDataTable().toString())
.putCustomAttribute("for_data", ">>>>> bucketed_data.size()=" + bucketed_data.size() + " i=" + i + "hourAgoData=" + hourAgoData.toString()) // .putCustomAttribute("for_data", ">>>>> bucketed_data.size()=" + bucketed_data.size() + " i=" + i + "hourAgoData=" + hourAgoData.toString())
.putCustomAttribute("past", past) // .putCustomAttribute("past", past)
); // );
} // }
} else {
if (L.isEnabled(L.AUTOSENS))
log.debug(">>>>> bucketed_data.size()=" + bucketed_data.size() + " i=" + i + " hourAgoData=" + "null");
} }
} }

View file

@ -81,7 +81,7 @@ public class MaintenancePlugin extends PluginBase {
LOG.debug("zipFile: {}", zipFile.getAbsolutePath()); LOG.debug("zipFile: {}", zipFile.getAbsolutePath());
File zip = this.zipLogs(zipFile, logs); File zip = this.zipLogs(zipFile, logs);
Uri attachementUri = FileProvider.getUriForFile(this.ctx, BuildConfig.APPLICATION_ID + ".provider", zip); Uri attachementUri = FileProvider.getUriForFile(this.ctx, BuildConfig.APPLICATION_ID + ".fileprovider", zip);
Intent emailIntent = this.sendMail(attachementUri, recipient, "Log Export"); Intent emailIntent = this.sendMail(attachementUri, recipient, "Log Export");
LOG.debug("sending emailIntent"); LOG.debug("sending emailIntent");
ctx.startActivity(emailIntent); ctx.startActivity(emailIntent);

View file

@ -28,7 +28,7 @@ public class BroadcastAckAlarm {
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent); LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent);
if(SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) { if(SP.getBoolean(R.string.key_nsclient_localbroadcasts, false)) {
bundle = new Bundle(); bundle = new Bundle();
bundle.putInt("level", originalAlarm.getLevel()); bundle.putInt("level", originalAlarm.getLevel());
bundle.putString("group", originalAlarm.getGroup()); bundle.putString("group", originalAlarm.getGroup());

View file

@ -24,7 +24,7 @@ public class BroadcastAlarm {
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent); LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent);
if(SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) { if(SP.getBoolean(R.string.key_nsclient_localbroadcasts, false)) {
bundle = new Bundle(); bundle = new Bundle();
bundle.putString("data", alarm.toString()); bundle.putString("data", alarm.toString());
intent = new Intent(Intents.ACTION_ALARM); intent = new Intent(Intents.ACTION_ALARM);

View file

@ -24,7 +24,7 @@ public class BroadcastAnnouncement {
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent); LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent);
if(SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) { if(SP.getBoolean(R.string.key_nsclient_localbroadcasts, false)) {
bundle = new Bundle(); bundle = new Bundle();
bundle.putString("data", announcement.toString()); bundle.putString("data", announcement.toString());
intent = new Intent(Intents.ACTION_ANNOUNCEMENT); intent = new Intent(Intents.ACTION_ANNOUNCEMENT);

View file

@ -26,7 +26,7 @@ public class BroadcastCals {
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent); LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent);
if(SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) { if(SP.getBoolean(R.string.key_nsclient_localbroadcasts, false)) {
bundle = new Bundle(); bundle = new Bundle();
bundle.putString("cals", cals.toString()); bundle.putString("cals", cals.toString());
bundle.putBoolean("delta", isDelta); bundle.putBoolean("delta", isDelta);

View file

@ -24,7 +24,7 @@ public class BroadcastClearAlarm {
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent); LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent);
if(SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) { if(SP.getBoolean(R.string.key_nsclient_localbroadcasts, false)) {
bundle = new Bundle(); bundle = new Bundle();
bundle.putString("data", clearalarm.toString()); bundle.putString("data", clearalarm.toString());
intent = new Intent(Intents.ACTION_CLEAR_ALARM); intent = new Intent(Intents.ACTION_CLEAR_ALARM);

View file

@ -29,7 +29,7 @@ public class BroadcastDeviceStatus {
LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent); LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent);
} }
if(SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) { if(SP.getBoolean(R.string.key_nsclient_localbroadcasts, false)) {
splitted = BroadcastTreatment.splitArray(statuses); splitted = BroadcastTreatment.splitArray(statuses);
for (JSONArray part : splitted) { for (JSONArray part : splitted) {
Bundle bundle = new Bundle(); Bundle bundle = new Bundle();

View file

@ -31,7 +31,7 @@ public class BroadcastFood {
LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent); LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent);
} }
if (SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) { if (SP.getBoolean(R.string.key_nsclient_localbroadcasts, false)) {
for (JSONArray part : splitted) { for (JSONArray part : splitted) {
Bundle bundle = new Bundle(); Bundle bundle = new Bundle();
bundle.putString("foods", part.toString()); bundle.putString("foods", part.toString());
@ -57,7 +57,7 @@ public class BroadcastFood {
LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent); LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent);
} }
if (SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) { if (SP.getBoolean(R.string.key_nsclient_localbroadcasts, false)) {
for (JSONArray part : splitted) { for (JSONArray part : splitted) {
Bundle bundle = new Bundle(); Bundle bundle = new Bundle();
bundle.putString("foods", part.toString()); bundle.putString("foods", part.toString());
@ -81,7 +81,7 @@ public class BroadcastFood {
LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent); LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent);
if (SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) { if (SP.getBoolean(R.string.key_nsclient_localbroadcasts, false)) {
bundle = new Bundle(); bundle = new Bundle();
bundle.putString("foods", foods.toString()); bundle.putString("foods", foods.toString());
bundle.putBoolean("delta", isDelta); bundle.putBoolean("delta", isDelta);

View file

@ -26,7 +26,7 @@ public class BroadcastMbgs {
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent); LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent);
if(SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) { if(SP.getBoolean(R.string.key_nsclient_localbroadcasts, false)) {
bundle = new Bundle(); bundle = new Bundle();
bundle.putString("mbgs", mbgs.toString()); bundle.putString("mbgs", mbgs.toString());
bundle.putBoolean("delta", isDelta); bundle.putBoolean("delta", isDelta);

View file

@ -26,7 +26,7 @@ public class BroadcastProfile {
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent); LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent);
if(SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) { if(SP.getBoolean(R.string.key_nsclient_localbroadcasts, false)) {
bundle = new Bundle(); bundle = new Bundle();
bundle.putString("profile", profile.getData().toString()); bundle.putString("profile", profile.getData().toString());
bundle.putBoolean("delta", isDelta); bundle.putBoolean("delta", isDelta);

View file

@ -31,7 +31,7 @@ public class BroadcastSgvs {
LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent); LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent);
} }
if(SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) { if(SP.getBoolean(R.string.key_nsclient_localbroadcasts, false)) {
for (JSONArray part : splitted) { for (JSONArray part : splitted) {
Bundle bundle = new Bundle(); Bundle bundle = new Bundle();
bundle.putString("sgvs", part.toString()); bundle.putString("sgvs", part.toString());

View file

@ -27,7 +27,7 @@ public class BroadcastStatus {
LocalBroadcastManager.getInstance(MainApp.instance()) LocalBroadcastManager.getInstance(MainApp.instance())
.sendBroadcast(createIntent(status, isDelta)); .sendBroadcast(createIntent(status, isDelta));
if(SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) { if(SP.getBoolean(R.string.key_nsclient_localbroadcasts, false)) {
context.sendBroadcast(createIntent(status, isDelta)); context.sendBroadcast(createIntent(status, isDelta));
} }
} }

View file

@ -36,7 +36,7 @@ public class BroadcastTreatment {
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent); LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent);
if (SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) { if (SP.getBoolean(R.string.key_nsclient_localbroadcasts, false)) {
bundle = new Bundle(); bundle = new Bundle();
bundle.putString("treatment", treatment.toString()); bundle.putString("treatment", treatment.toString());
bundle.putBoolean("delta", isDelta); bundle.putBoolean("delta", isDelta);
@ -60,7 +60,7 @@ public class BroadcastTreatment {
LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent); LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent);
} }
if (SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) { if (SP.getBoolean(R.string.key_nsclient_localbroadcasts, false)) {
splitted = splitArray(treatments); splitted = splitArray(treatments);
for (JSONArray part : splitted) { for (JSONArray part : splitted) {
Bundle bundle = new Bundle(); Bundle bundle = new Bundle();
@ -87,7 +87,7 @@ public class BroadcastTreatment {
LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent); LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent);
} }
if (SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) { if (SP.getBoolean(R.string.key_nsclient_localbroadcasts, false)) {
splitted = splitArray(treatments); splitted = splitArray(treatments);
for (JSONArray part : splitted) { for (JSONArray part : splitted) {
Bundle bundle = new Bundle(); Bundle bundle = new Bundle();
@ -112,7 +112,7 @@ public class BroadcastTreatment {
LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent); LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent);
if (SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) { if (SP.getBoolean(R.string.key_nsclient_localbroadcasts, false)) {
bundle = new Bundle(); bundle = new Bundle();
bundle.putString("treatments", treatments.toString()); bundle.putString("treatments", treatments.toString());
bundle.putBoolean("delta", isDelta); bundle.putBoolean("delta", isDelta);

View file

@ -24,7 +24,7 @@ public class BroadcastUrgentAlarm {
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent); LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent);
if(SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) { if(SP.getBoolean(R.string.key_nsclient_localbroadcasts, false)) {
bundle = new Bundle(); bundle = new Bundle();
bundle.putString("data", urgentalarm.toString()); bundle.putString("data", urgentalarm.toString());
intent = new Intent(Intents.ACTION_URGENT_ALARM); intent = new Intent(Intents.ACTION_URGENT_ALARM);

View file

@ -15,6 +15,7 @@ import java.util.HashMap;
import java.util.Iterator; import java.util.Iterator;
import java.util.Map; import java.util.Map;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.ConstraintsObjectives.ObjectivesPlugin; import info.nightscout.androidaps.plugins.ConstraintsObjectives.ObjectivesPlugin;
@ -174,10 +175,14 @@ public class NSDeviceStatus {
public Spanned getPumpStatus() { public Spanned getPumpStatus() {
//String[] ALL_STATUS_FIELDS = {"reservoir", "battery", "clock", "status", "device"}; //String[] ALL_STATUS_FIELDS = {"reservoir", "battery", "clock", "status", "device"};
StringBuilder string = new StringBuilder();
string.append("<span style=\"color:" + MainApp.gs(R.color.defaulttext).replace("#ff", "#") + "\">");
string.append(MainApp.gs(R.string.pump));
string.append(": </span>");
if (deviceStatusPumpData == null) if (deviceStatusPumpData == null)
return Html.fromHtml(""); return Html.fromHtml("");
StringBuilder string = new StringBuilder();
// test warning level // test warning level
int level = Levels.INFO; int level = Levels.INFO;
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
@ -329,6 +334,10 @@ public class NSDeviceStatus {
public Spanned getOpenApsStatus() { public Spanned getOpenApsStatus() {
StringBuilder string = new StringBuilder(); StringBuilder string = new StringBuilder();
string.append("<span style=\"color:" + MainApp.gs(R.color.defaulttext).replace("#ff", "#") + "\">");
string.append(MainApp.gs(R.string.openaps_short));
string.append(": </span>");
// test warning level // test warning level
int level = Levels.INFO; int level = Levels.INFO;
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
@ -426,6 +435,26 @@ public class NSDeviceStatus {
return minBattery + "%"; return minBattery + "%";
} }
public Spanned getUploaderStatusSpanned() {
StringBuilder string = new StringBuilder();
string.append("<span style=\"color:" + MainApp.gs(R.color.defaulttext).replace("#ff", "#") + "\">");
string.append(MainApp.gs(R.string.uploader_short));
string.append(": </span>");
Iterator iter = uploaders.entrySet().iterator();
int minBattery = 100;
while (iter.hasNext()) {
Map.Entry pair = (Map.Entry) iter.next();
Uploader uploader = (Uploader) pair.getValue();
if (minBattery > uploader.battery)
minBattery = uploader.battery;
}
string.append(minBattery);
string.append("%");
return Html.fromHtml(string.toString());
}
public Spanned getExtendedUploaderStatus() { public Spanned getExtendedUploaderStatus() {
StringBuilder string = new StringBuilder(); StringBuilder string = new StringBuilder();

View file

@ -22,6 +22,7 @@ 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.OpenAPSMA.events.EventOpenAPSUpdateGui; import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateGui;
import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateResultGui; import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateResultGui;
import info.nightscout.utils.DateUtil;
import info.nightscout.utils.FabricPrivacy; import info.nightscout.utils.FabricPrivacy;
import info.nightscout.utils.JSONFormatter; import info.nightscout.utils.JSONFormatter;
@ -108,8 +109,8 @@ public class OpenAPSAMAFragment extends SubscriberFragment implements View.OnCli
mealDataView.setText(JSONFormatter.format(determineBasalAdapterAMAJS.getMealDataParam())); mealDataView.setText(JSONFormatter.format(determineBasalAdapterAMAJS.getMealDataParam()));
scriptdebugView.setText(determineBasalAdapterAMAJS.getScriptDebug()); scriptdebugView.setText(determineBasalAdapterAMAJS.getScriptDebug());
} }
if (OpenAPSAMAPlugin.getPlugin().lastAPSRun != null) { if (OpenAPSAMAPlugin.getPlugin().lastAPSRun != 0) {
lastRunView.setText(OpenAPSAMAPlugin.getPlugin().lastAPSRun.toLocaleString()); lastRunView.setText(DateUtil.dateAndTimeFullString(OpenAPSAMAPlugin.getPlugin().lastAPSRun));
} }
if (OpenAPSAMAPlugin.getPlugin().lastAutosensResult != null) { if (OpenAPSAMAPlugin.getPlugin().lastAutosensResult != null) {
autosensDataView.setText(JSONFormatter.format(OpenAPSAMAPlugin.getPlugin().lastAutosensResult.json())); autosensDataView.setText(JSONFormatter.format(OpenAPSAMAPlugin.getPlugin().lastAutosensResult.json()));

View file

@ -4,8 +4,6 @@ import org.json.JSONException;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.Date;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.GlucoseStatus; import info.nightscout.androidaps.data.GlucoseStatus;
@ -52,11 +50,11 @@ public class OpenAPSAMAPlugin extends PluginBase implements APSInterface {
// last values // last values
DetermineBasalAdapterAMAJS lastDetermineBasalAdapterAMAJS = null; DetermineBasalAdapterAMAJS lastDetermineBasalAdapterAMAJS = null;
Date lastAPSRun = null; long lastAPSRun = 0;
DetermineBasalResultAMA lastAPSResult = null; DetermineBasalResultAMA lastAPSResult = null;
AutosensResult lastAutosensResult = null; AutosensResult lastAutosensResult = null;
public OpenAPSAMAPlugin() { private OpenAPSAMAPlugin() {
super(new PluginDescription() super(new PluginDescription()
.mainType(PluginType.APS) .mainType(PluginType.APS)
.fragmentClass(OpenAPSAMAFragment.class.getName()) .fragmentClass(OpenAPSAMAFragment.class.getName())
@ -85,7 +83,7 @@ public class OpenAPSAMAPlugin extends PluginBase implements APSInterface {
} }
@Override @Override
public Date getLastAPSRun() { public long getLastAPSRun() {
return lastAPSRun; return lastAPSRun;
} }
@ -132,13 +130,13 @@ public class OpenAPSAMAPlugin extends PluginBase implements APSInterface {
minBg = Round.roundTo(minBg, 0.1d); minBg = Round.roundTo(minBg, 0.1d);
maxBg = Round.roundTo(maxBg, 0.1d); maxBg = Round.roundTo(maxBg, 0.1d);
Date start = new Date(); long start = System.currentTimeMillis();
Date startPart = new Date(); long startPart = System.currentTimeMillis();
IobTotal[] iobArray = IobCobCalculatorPlugin.getPlugin().calculateIobArrayInDia(profile); IobTotal[] iobArray = IobCobCalculatorPlugin.getPlugin().calculateIobArrayInDia(profile);
if (L.isEnabled(L.APS)) if (L.isEnabled(L.APS))
Profiler.log(log, "calculateIobArrayInDia()", startPart); Profiler.log(log, "calculateIobArrayInDia()", startPart);
startPart = new Date(); startPart = System.currentTimeMillis();
MealData mealData = TreatmentsPlugin.getPlugin().getMealData(); MealData mealData = TreatmentsPlugin.getPlugin().getMealData();
if (L.isEnabled(L.APS)) if (L.isEnabled(L.APS))
Profiler.log(log, "getMealData()", startPart); Profiler.log(log, "getMealData()", startPart);
@ -170,7 +168,7 @@ public class OpenAPSAMAPlugin extends PluginBase implements APSInterface {
if (!HardLimits.checkOnlyHardLimits(pump.getBaseBasalRate(), "current_basal", 0.01, HardLimits.maxBasal())) if (!HardLimits.checkOnlyHardLimits(pump.getBaseBasalRate(), "current_basal", 0.01, HardLimits.maxBasal()))
return; return;
startPart = new Date(); startPart = System.currentTimeMillis();
if (MainApp.getConstraintChecker().isAutosensModeEnabled().value()) { if (MainApp.getConstraintChecker().isAutosensModeEnabled().value()) {
AutosensData autosensData = IobCobCalculatorPlugin.getPlugin().getLastAutosensDataSynchronized("OpenAPSPlugin"); AutosensData autosensData = IobCobCalculatorPlugin.getPlugin().getLastAutosensDataSynchronized("OpenAPSPlugin");
if (autosensData == null) { if (autosensData == null) {
@ -187,7 +185,7 @@ public class OpenAPSAMAPlugin extends PluginBase implements APSInterface {
if (L.isEnabled(L.APS)) if (L.isEnabled(L.APS))
Profiler.log(log, "AMA data gathering", start); Profiler.log(log, "AMA data gathering", start);
start = new Date(); start = System.currentTimeMillis();
try { try {
determineBasalAdapterAMAJS.setData(profile, maxIob, maxBasal, minBg, maxBg, targetBg, ConfigBuilderPlugin.getActivePump().getBaseBasalRate(), iobArray, glucoseStatus, mealData, determineBasalAdapterAMAJS.setData(profile, maxIob, maxBasal, minBg, maxBg, targetBg, ConfigBuilderPlugin.getActivePump().getBaseBasalRate(), iobArray, glucoseStatus, mealData,
@ -219,7 +217,7 @@ public class OpenAPSAMAPlugin extends PluginBase implements APSInterface {
determineBasalResultAMA.iob = iobArray[0]; determineBasalResultAMA.iob = iobArray[0];
Date now = new Date(); long now = System.currentTimeMillis();
try { try {
determineBasalResultAMA.json.put("timestamp", DateUtil.toISOString(now)); determineBasalResultAMA.json.put("timestamp", DateUtil.toISOString(now));

View file

@ -15,6 +15,7 @@ import info.nightscout.androidaps.R;
import info.nightscout.androidaps.plugins.Common.SubscriberFragment; import info.nightscout.androidaps.plugins.Common.SubscriberFragment;
import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateGui; import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateGui;
import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateResultGui; import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateResultGui;
import info.nightscout.utils.DateUtil;
import info.nightscout.utils.FabricPrivacy; import info.nightscout.utils.FabricPrivacy;
import info.nightscout.utils.JSONFormatter; import info.nightscout.utils.JSONFormatter;
@ -94,8 +95,8 @@ public class OpenAPSMAFragment extends SubscriberFragment implements View.OnClic
profileView.setText(JSONFormatter.format(determineBasalAdapterMAJS.getProfileParam())); profileView.setText(JSONFormatter.format(determineBasalAdapterMAJS.getProfileParam()));
mealDataView.setText(JSONFormatter.format(determineBasalAdapterMAJS.getMealDataParam())); mealDataView.setText(JSONFormatter.format(determineBasalAdapterMAJS.getMealDataParam()));
} }
if (OpenAPSMAPlugin.getPlugin().lastAPSRun != null) { if (OpenAPSMAPlugin.getPlugin().lastAPSRun != 0) {
lastRunView.setText(OpenAPSMAPlugin.getPlugin().lastAPSRun.toLocaleString()); lastRunView.setText(DateUtil.dateAndTimeFullString(OpenAPSMAPlugin.getPlugin().lastAPSRun));
} }
}); });
} }

View file

@ -4,8 +4,6 @@ import org.json.JSONException;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.Date;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.GlucoseStatus; import info.nightscout.androidaps.data.GlucoseStatus;
@ -52,10 +50,10 @@ public class OpenAPSMAPlugin extends PluginBase implements APSInterface {
// last values // last values
DetermineBasalAdapterMAJS lastDetermineBasalAdapterMAJS = null; DetermineBasalAdapterMAJS lastDetermineBasalAdapterMAJS = null;
Date lastAPSRun = null; long lastAPSRun = 0;
DetermineBasalResultMA lastAPSResult = null; DetermineBasalResultMA lastAPSResult = null;
public OpenAPSMAPlugin() { private OpenAPSMAPlugin() {
super(new PluginDescription() super(new PluginDescription()
.mainType(PluginType.APS) .mainType(PluginType.APS)
.fragmentClass(OpenAPSMAFragment.class.getName()) .fragmentClass(OpenAPSMAFragment.class.getName())
@ -84,7 +82,7 @@ public class OpenAPSMAPlugin extends PluginBase implements APSInterface {
} }
@Override @Override
public Date getLastAPSRun() { public long getLastAPSRun() {
return lastAPSRun; return lastAPSRun;
} }
@ -93,7 +91,7 @@ public class OpenAPSMAPlugin extends PluginBase implements APSInterface {
if (L.isEnabled(L.APS)) if (L.isEnabled(L.APS))
log.debug("invoke from " + initiator + " tempBasalFallback: " + tempBasalFallback); log.debug("invoke from " + initiator + " tempBasalFallback: " + tempBasalFallback);
lastAPSResult = null; lastAPSResult = null;
DetermineBasalAdapterMAJS determineBasalAdapterMAJS = null; DetermineBasalAdapterMAJS determineBasalAdapterMAJS;
determineBasalAdapterMAJS = new DetermineBasalAdapterMAJS(new ScriptReader(MainApp.instance().getBaseContext())); determineBasalAdapterMAJS = new DetermineBasalAdapterMAJS(new ScriptReader(MainApp.instance().getBaseContext()));
GlucoseStatus glucoseStatus = GlucoseStatus.getGlucoseStatusData(); GlucoseStatus glucoseStatus = GlucoseStatus.getGlucoseStatusData();
@ -132,7 +130,7 @@ public class OpenAPSMAPlugin extends PluginBase implements APSInterface {
minBg = Round.roundTo(minBg, 0.1d); minBg = Round.roundTo(minBg, 0.1d);
maxBg = Round.roundTo(maxBg, 0.1d); maxBg = Round.roundTo(maxBg, 0.1d);
Date start = new Date(); long start = System.currentTimeMillis();
TreatmentsPlugin.getPlugin().updateTotalIOBTreatments(); TreatmentsPlugin.getPlugin().updateTotalIOBTreatments();
TreatmentsPlugin.getPlugin().updateTotalIOBTempBasals(); TreatmentsPlugin.getPlugin().updateTotalIOBTempBasals();
IobTotal bolusIob = TreatmentsPlugin.getPlugin().getLastCalculationTreatments(); IobTotal bolusIob = TreatmentsPlugin.getPlugin().getLastCalculationTreatments();
@ -159,7 +157,7 @@ public class OpenAPSMAPlugin extends PluginBase implements APSInterface {
if (!checkOnlyHardLimits(profile.getDia(), "dia", HardLimits.MINDIA, HardLimits.MAXDIA)) if (!checkOnlyHardLimits(profile.getDia(), "dia", HardLimits.MINDIA, HardLimits.MAXDIA))
return; return;
if (!checkOnlyHardLimits(profile.getIcTimeFromMidnight(profile.secondsFromMidnight()), "carbratio", HardLimits.MINIC, HardLimits.MAXIC)) if (!checkOnlyHardLimits(profile.getIcTimeFromMidnight(Profile.secondsFromMidnight()), "carbratio", HardLimits.MINIC, HardLimits.MAXIC))
return; return;
if (!checkOnlyHardLimits(Profile.toMgdl(profile.getIsf(), units), "sens", HardLimits.MINISF, HardLimits.MAXISF)) if (!checkOnlyHardLimits(Profile.toMgdl(profile.getIsf(), units), "sens", HardLimits.MINISF, HardLimits.MAXISF))
return; return;
@ -168,7 +166,7 @@ public class OpenAPSMAPlugin extends PluginBase implements APSInterface {
if (!checkOnlyHardLimits(pump.getBaseBasalRate(), "current_basal", 0.01, HardLimits.maxBasal())) if (!checkOnlyHardLimits(pump.getBaseBasalRate(), "current_basal", 0.01, HardLimits.maxBasal()))
return; return;
start = new Date(); start = System.currentTimeMillis();
try { try {
determineBasalAdapterMAJS.setData(profile, maxIob, maxBasal, minBg, maxBg, targetBg, ConfigBuilderPlugin.getActivePump().getBaseBasalRate(), iobTotal, glucoseStatus, mealData); determineBasalAdapterMAJS.setData(profile, maxIob, maxBasal, minBg, maxBg, targetBg, ConfigBuilderPlugin.getActivePump().getBaseBasalRate(), iobTotal, glucoseStatus, mealData);
} catch (JSONException e) { } catch (JSONException e) {
@ -205,7 +203,7 @@ public class OpenAPSMAPlugin extends PluginBase implements APSInterface {
lastDetermineBasalAdapterMAJS = determineBasalAdapterMAJS; lastDetermineBasalAdapterMAJS = determineBasalAdapterMAJS;
lastAPSResult = determineBasalResultMA; lastAPSResult = determineBasalResultMA;
lastAPSRun = new Date(now); lastAPSRun = now;
MainApp.bus().post(new EventOpenAPSUpdateGui()); MainApp.bus().post(new EventOpenAPSUpdateGui());
} }

View file

@ -25,6 +25,7 @@ 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.OpenAPSMA.events.EventOpenAPSUpdateGui; import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateGui;
import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateResultGui; import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateResultGui;
import info.nightscout.utils.DateUtil;
import info.nightscout.utils.FabricPrivacy; import info.nightscout.utils.FabricPrivacy;
import info.nightscout.utils.JSONFormatter; import info.nightscout.utils.JSONFormatter;
@ -111,8 +112,8 @@ public class OpenAPSSMBFragment extends SubscriberFragment {
if (lastAPSResult != null && lastAPSResult.inputConstraints != null) if (lastAPSResult != null && lastAPSResult.inputConstraints != null)
constraintsView.setText(lastAPSResult.inputConstraints.getReasons().trim()); constraintsView.setText(lastAPSResult.inputConstraints.getReasons().trim());
} }
if (plugin.lastAPSRun != null) { if (plugin.lastAPSRun != 0) {
lastRunView.setText(plugin.lastAPSRun.toLocaleString().trim()); lastRunView.setText(DateUtil.dateAndTimeFullString(plugin.lastAPSRun));
} }
if (plugin.lastAutosensResult != null) { if (plugin.lastAutosensResult != null) {
autosensDataView.setText(JSONFormatter.format(plugin.lastAutosensResult.json()).toString().trim()); autosensDataView.setText(JSONFormatter.format(plugin.lastAutosensResult.json()).toString().trim());

View file

@ -55,7 +55,7 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface {
// last values // last values
DetermineBasalAdapterSMBJS lastDetermineBasalAdapterSMBJS = null; DetermineBasalAdapterSMBJS lastDetermineBasalAdapterSMBJS = null;
Date lastAPSRun = null; long lastAPSRun = 0;
DetermineBasalResultSMB lastAPSResult = null; DetermineBasalResultSMB lastAPSResult = null;
AutosensResult lastAutosensResult = null; AutosensResult lastAutosensResult = null;
@ -88,7 +88,7 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface {
} }
@Override @Override
public Date getLastAPSRun() { public long getLastAPSRun() {
return lastAPSRun; return lastAPSRun;
} }
@ -139,13 +139,13 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface {
minBg = Round.roundTo(minBg, 0.1d); minBg = Round.roundTo(minBg, 0.1d);
maxBg = Round.roundTo(maxBg, 0.1d); maxBg = Round.roundTo(maxBg, 0.1d);
Date start = new Date(); long start = System.currentTimeMillis();
Date startPart = new Date(); long startPart = System.currentTimeMillis();
IobTotal[] iobArray = IobCobCalculatorPlugin.getPlugin().calculateIobArrayForSMB(profile); IobTotal[] iobArray = IobCobCalculatorPlugin.getPlugin().calculateIobArrayForSMB(profile);
if (L.isEnabled(L.APS)) if (L.isEnabled(L.APS))
Profiler.log(log, "calculateIobArrayInDia()", startPart); Profiler.log(log, "calculateIobArrayInDia()", startPart);
startPart = new Date(); startPart = System.currentTimeMillis();
MealData mealData = TreatmentsPlugin.getPlugin().getMealData(); MealData mealData = TreatmentsPlugin.getPlugin().getMealData();
if (L.isEnabled(L.APS)) if (L.isEnabled(L.APS))
Profiler.log(log, "getMealData()", startPart); Profiler.log(log, "getMealData()", startPart);
@ -177,7 +177,7 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface {
if (!checkOnlyHardLimits(pump.getBaseBasalRate(), "current_basal", 0.01, HardLimits.maxBasal())) if (!checkOnlyHardLimits(pump.getBaseBasalRate(), "current_basal", 0.01, HardLimits.maxBasal()))
return; return;
startPart = new Date(); startPart = System.currentTimeMillis();
if (MainApp.getConstraintChecker().isAutosensModeEnabled().value()) { if (MainApp.getConstraintChecker().isAutosensModeEnabled().value()) {
AutosensData autosensData = IobCobCalculatorPlugin.getPlugin().getLastAutosensDataSynchronized("OpenAPSPlugin"); AutosensData autosensData = IobCobCalculatorPlugin.getPlugin().getLastAutosensDataSynchronized("OpenAPSPlugin");
if (autosensData == null) { if (autosensData == null) {
@ -203,7 +203,7 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface {
if (L.isEnabled(L.APS)) if (L.isEnabled(L.APS))
Profiler.log(log, "SMB data gathering", start); Profiler.log(log, "SMB data gathering", start);
start = new Date(); start = System.currentTimeMillis();
try { try {
determineBasalAdapterSMBJS.setData(profile, maxIob, maxBasal, minBg, maxBg, targetBg, ConfigBuilderPlugin.getActivePump().getBaseBasalRate(), iobArray, glucoseStatus, mealData, determineBasalAdapterSMBJS.setData(profile, maxIob, maxBasal, minBg, maxBg, targetBg, ConfigBuilderPlugin.getActivePump().getBaseBasalRate(), iobArray, glucoseStatus, mealData,
lastAutosensResult.ratio, //autosensDataRatio lastAutosensResult.ratio, //autosensDataRatio
@ -248,7 +248,7 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface {
lastDetermineBasalAdapterSMBJS = determineBasalAdapterSMBJS; lastDetermineBasalAdapterSMBJS = determineBasalAdapterSMBJS;
lastAPSResult = determineBasalResultSMB; lastAPSResult = determineBasalResultSMB;
lastAPSRun = new Date(now); lastAPSRun = now;
MainApp.bus().post(new EventOpenAPSUpdateGui()); MainApp.bus().post(new EventOpenAPSUpdateGui());
//deviceStatus.suggested = determineBasalResultAMA.json; //deviceStatus.suggested = determineBasalResultAMA.json;

View file

@ -483,9 +483,10 @@ public class WizardDialog extends DialogFragment implements OnClickListener, Com
return; // not initialized yet return; // not initialized yet
String selectedAlternativeProfile = profileSpinner.getSelectedItem().toString(); String selectedAlternativeProfile = profileSpinner.getSelectedItem().toString();
Profile specificProfile; Profile specificProfile;
if (selectedAlternativeProfile.equals(MainApp.gs(R.string.active))) if (selectedAlternativeProfile.equals(MainApp.gs(R.string.active))) {
specificProfile = ProfileFunctions.getInstance().getProfile(); specificProfile = ProfileFunctions.getInstance().getProfile();
else selectedAlternativeProfile = MainApp.getConfigBuilder().getActiveProfileInterface().getProfileName();
} else
specificProfile = profileStore.getSpecificProfile(selectedAlternativeProfile); specificProfile = profileStore.getSpecificProfile(selectedAlternativeProfile);
// Entered values // Entered values
@ -579,12 +580,15 @@ public class WizardDialog extends DialogFragment implements OnClickListener, Com
boluscalcJSON = new JSONObject(); boluscalcJSON = new JSONObject();
try { try {
boluscalcJSON.put("profile", selectedAlternativeProfile); boluscalcJSON.put("profile", selectedAlternativeProfile);
boluscalcJSON.put("notes", notesEdit.getText());
boluscalcJSON.put("eventTime", DateUtil.toISOString(new Date())); boluscalcJSON.put("eventTime", DateUtil.toISOString(new Date()));
boluscalcJSON.put("targetBGLow", wizard.targetBGLow); boluscalcJSON.put("targetBGLow", wizard.targetBGLow);
boluscalcJSON.put("targetBGHigh", wizard.targetBGHigh); boluscalcJSON.put("targetBGHigh", wizard.targetBGHigh);
boluscalcJSON.put("isf", wizard.sens); boluscalcJSON.put("isf", wizard.sens);
boluscalcJSON.put("ic", wizard.ic); boluscalcJSON.put("ic", wizard.ic);
boluscalcJSON.put("iob", -(wizard.insulingFromBolusIOB + wizard.insulingFromBasalsIOB)); boluscalcJSON.put("iob", -(wizard.insulingFromBolusIOB + wizard.insulingFromBasalsIOB));
boluscalcJSON.put("bolusiob", wizard.insulingFromBolusIOB);
boluscalcJSON.put("basaliob", wizard.insulingFromBasalsIOB);
boluscalcJSON.put("bolusiobused", bolusIobCheckbox.isChecked()); boluscalcJSON.put("bolusiobused", bolusIobCheckbox.isChecked());
boluscalcJSON.put("basaliobused", basalIobCheckbox.isChecked()); boluscalcJSON.put("basaliobused", basalIobCheckbox.isChecked());
boluscalcJSON.put("bg", c_bg); boluscalcJSON.put("bg", c_bg);
@ -594,11 +598,18 @@ public class WizardDialog extends DialogFragment implements OnClickListener, Com
boluscalcJSON.put("insulincarbs", wizard.insulinFromCarbs); boluscalcJSON.put("insulincarbs", wizard.insulinFromCarbs);
boluscalcJSON.put("carbs", c_carbs); boluscalcJSON.put("carbs", c_carbs);
boluscalcJSON.put("cob", c_cob); boluscalcJSON.put("cob", c_cob);
boluscalcJSON.put("cobused", cobCheckbox.isChecked());
boluscalcJSON.put("insulincob", wizard.insulinFromCOB); boluscalcJSON.put("insulincob", wizard.insulinFromCOB);
boluscalcJSON.put("othercorrection", corrAfterConstraint); boluscalcJSON.put("othercorrection", corrAfterConstraint);
boluscalcJSON.put("insulinsuperbolus", wizard.insulinFromSuperBolus); boluscalcJSON.put("insulinsuperbolus", wizard.insulinFromSuperBolus);
boluscalcJSON.put("insulintrend", wizard.insulinFromTrend); boluscalcJSON.put("insulintrend", wizard.insulinFromTrend);
boluscalcJSON.put("insulin", calculatedTotalInsulin); boluscalcJSON.put("insulin", calculatedTotalInsulin);
boluscalcJSON.put("superbolusused", superbolusCheckbox.isChecked());
boluscalcJSON.put("insulinsuperbolus", wizard.insulinFromSuperBolus);
boluscalcJSON.put("trendused", bgtrendCheckbox.isChecked());
boluscalcJSON.put("insulintrend", wizard.insulinFromTrend);
boluscalcJSON.put("trend", bgTrend.getText());
boluscalcJSON.put("ttused", ttCheckbox.isChecked());
} catch (JSONException e) { } catch (JSONException e) {
log.error("Unhandled exception", e); log.error("Unhandled exception", e);
} }

View file

@ -66,6 +66,7 @@ import info.nightscout.androidaps.db.ExtendedBolus;
import info.nightscout.androidaps.db.Source; import info.nightscout.androidaps.db.Source;
import info.nightscout.androidaps.db.TempTarget; import info.nightscout.androidaps.db.TempTarget;
import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.events.EventAcceptOpenLoopChange;
import info.nightscout.androidaps.events.EventCareportalEventChange; import info.nightscout.androidaps.events.EventCareportalEventChange;
import info.nightscout.androidaps.events.EventExtendedBolusChange; import info.nightscout.androidaps.events.EventExtendedBolusChange;
import info.nightscout.androidaps.events.EventInitializationChanged; import info.nightscout.androidaps.events.EventInitializationChanged;
@ -86,7 +87,6 @@ import info.nightscout.androidaps.plugins.Careportal.Dialogs.NewNSTreatmentDialo
import info.nightscout.androidaps.plugins.Careportal.OptionsToShow; import info.nightscout.androidaps.plugins.Careportal.OptionsToShow;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.ConstraintsObjectives.ObjectivesPlugin;
import info.nightscout.androidaps.plugins.IobCobCalculator.AutosensData; import info.nightscout.androidaps.plugins.IobCobCalculator.AutosensData;
import info.nightscout.androidaps.plugins.IobCobCalculator.CobInfo; import info.nightscout.androidaps.plugins.IobCobCalculator.CobInfo;
import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin;
@ -95,6 +95,7 @@ import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventIobCalcul
import info.nightscout.androidaps.plugins.Loop.APSResult; import info.nightscout.androidaps.plugins.Loop.APSResult;
import info.nightscout.androidaps.plugins.Loop.LoopPlugin; import info.nightscout.androidaps.plugins.Loop.LoopPlugin;
import info.nightscout.androidaps.plugins.Loop.events.EventNewOpenLoopNotification; import info.nightscout.androidaps.plugins.Loop.events.EventNewOpenLoopNotification;
import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSDeviceStatus; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSDeviceStatus;
import info.nightscout.androidaps.plugins.Overview.Dialogs.CalibrationDialog; import info.nightscout.androidaps.plugins.Overview.Dialogs.CalibrationDialog;
import info.nightscout.androidaps.plugins.Overview.Dialogs.ErrorHelperActivity; import info.nightscout.androidaps.plugins.Overview.Dialogs.ErrorHelperActivity;
@ -111,14 +112,12 @@ import info.nightscout.androidaps.plugins.Source.SourceXdripPlugin;
import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin; import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin;
import info.nightscout.androidaps.plugins.Treatments.fragments.ProfileViewerDialog; import info.nightscout.androidaps.plugins.Treatments.fragments.ProfileViewerDialog;
import info.nightscout.androidaps.plugins.Wear.ActionStringHandler; import info.nightscout.androidaps.plugins.Wear.ActionStringHandler;
import info.nightscout.androidaps.events.EventAcceptOpenLoopChange;
import info.nightscout.androidaps.queue.Callback; import info.nightscout.androidaps.queue.Callback;
import info.nightscout.utils.BolusWizard; import info.nightscout.utils.BolusWizard;
import info.nightscout.utils.DateUtil; import info.nightscout.utils.DateUtil;
import info.nightscout.utils.DecimalFormatter; import info.nightscout.utils.DecimalFormatter;
import info.nightscout.utils.DefaultValueHelper; import info.nightscout.utils.DefaultValueHelper;
import info.nightscout.utils.FabricPrivacy; import info.nightscout.utils.FabricPrivacy;
import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload;
import info.nightscout.utils.OKDialog; import info.nightscout.utils.OKDialog;
import info.nightscout.utils.Profiler; import info.nightscout.utils.Profiler;
import info.nightscout.utils.SP; import info.nightscout.utils.SP;
@ -189,8 +188,6 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
Handler sLoopHandler = new Handler(); Handler sLoopHandler = new Handler();
Runnable sRefreshLoop = null; Runnable sRefreshLoop = null;
final Object updateSync = new Object();
public enum CHARTTYPE {PRE, BAS, IOB, COB, DEV, SEN, DEVSLOPE} public enum CHARTTYPE {PRE, BAS, IOB, COB, DEV, SEN, DEVSLOPE}
private static final ScheduledExecutorService worker = Executors.newSingleThreadScheduledExecutor(); private static final ScheduledExecutorService worker = Executors.newSingleThreadScheduledExecutor();
@ -320,15 +317,12 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
rangeToDisplay = SP.getInt(R.string.key_rangetodisplay, 6); rangeToDisplay = SP.getInt(R.string.key_rangetodisplay, 6);
bgGraph.setOnLongClickListener(new View.OnLongClickListener() { bgGraph.setOnLongClickListener(v -> {
@Override rangeToDisplay += 6;
public boolean onLongClick(View v) { rangeToDisplay = rangeToDisplay > 24 ? 6 : rangeToDisplay;
rangeToDisplay += 6; SP.putInt(R.string.key_rangetodisplay, rangeToDisplay);
rangeToDisplay = rangeToDisplay > 24 ? 6 : rangeToDisplay; updateGUI("rangeChange");
SP.putInt(R.string.key_rangetodisplay, rangeToDisplay); return false;
updateGUI("rangeChange");
return false;
}
}); });
setupChartMenu(view); setupChartMenu(view);
@ -338,114 +332,111 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
private void setupChartMenu(View view) { private void setupChartMenu(View view) {
chartButton = (ImageButton) view.findViewById(R.id.overview_chartMenuButton); chartButton = (ImageButton) view.findViewById(R.id.overview_chartMenuButton);
chartButton.setOnClickListener(new View.OnClickListener() { chartButton.setOnClickListener(v -> {
@Override final LoopPlugin.LastRun finalLastRun = LoopPlugin.lastRun;
public void onClick(View v) { boolean predictionsAvailable;
final LoopPlugin.LastRun finalLastRun = LoopPlugin.lastRun; if (Config.APS)
boolean predictionsAvailable; predictionsAvailable = finalLastRun != null && finalLastRun.request.hasPredictions;
if (Config.APS) else if (Config.NSCLIENT)
predictionsAvailable = finalLastRun != null && finalLastRun.request.hasPredictions; predictionsAvailable = true;
else if (Config.NSCLIENT) else
predictionsAvailable = true; predictionsAvailable = false;
else
predictionsAvailable = false;
MenuItem item; MenuItem item;
CharSequence title; CharSequence title;
SpannableString s; SpannableString s;
PopupMenu popup = new PopupMenu(v.getContext(), v); PopupMenu popup = new PopupMenu(v.getContext(), v);
if (predictionsAvailable) { if (predictionsAvailable) {
item = popup.getMenu().add(Menu.NONE, CHARTTYPE.PRE.ordinal(), Menu.NONE, "Predictions"); item = popup.getMenu().add(Menu.NONE, CHARTTYPE.PRE.ordinal(), Menu.NONE, "Predictions");
title = item.getTitle();
s = new SpannableString(title);
s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.prediction, null)), 0, s.length(), 0);
item.setTitle(s);
item.setCheckable(true);
item.setChecked(SP.getBoolean("showprediction", true));
}
item = popup.getMenu().add(Menu.NONE, CHARTTYPE.BAS.ordinal(), Menu.NONE, MainApp.gs(R.string.overview_show_basals));
title = item.getTitle(); title = item.getTitle();
s = new SpannableString(title); s = new SpannableString(title);
s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.basal, null)), 0, s.length(), 0); s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.prediction, null)), 0, s.length(), 0);
item.setTitle(s); item.setTitle(s);
item.setCheckable(true); item.setCheckable(true);
item.setChecked(SP.getBoolean("showbasals", true)); item.setChecked(SP.getBoolean("showprediction", true));
item = popup.getMenu().add(Menu.NONE, CHARTTYPE.IOB.ordinal(), Menu.NONE, MainApp.gs(R.string.overview_show_iob));
title = item.getTitle();
s = new SpannableString(title);
s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.iob, null)), 0, s.length(), 0);
item.setTitle(s);
item.setCheckable(true);
item.setChecked(SP.getBoolean("showiob", true));
item = popup.getMenu().add(Menu.NONE, CHARTTYPE.COB.ordinal(), Menu.NONE, MainApp.gs(R.string.overview_show_cob));
title = item.getTitle();
s = new SpannableString(title);
s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.cob, null)), 0, s.length(), 0);
item.setTitle(s);
item.setCheckable(true);
item.setChecked(SP.getBoolean("showcob", true));
item = popup.getMenu().add(Menu.NONE, CHARTTYPE.DEV.ordinal(), Menu.NONE, MainApp.gs(R.string.overview_show_deviations));
title = item.getTitle();
s = new SpannableString(title);
s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.deviations, null)), 0, s.length(), 0);
item.setTitle(s);
item.setCheckable(true);
item.setChecked(SP.getBoolean("showdeviations", false));
item = popup.getMenu().add(Menu.NONE, CHARTTYPE.SEN.ordinal(), Menu.NONE, MainApp.gs(R.string.overview_show_sensitivity));
title = item.getTitle();
s = new SpannableString(title);
s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.ratio, null)), 0, s.length(), 0);
item.setTitle(s);
item.setCheckable(true);
item.setChecked(SP.getBoolean("showratios", false));
if (MainApp.devBranch) {
item = popup.getMenu().add(Menu.NONE, CHARTTYPE.DEVSLOPE.ordinal(), Menu.NONE, "Deviation slope");
title = item.getTitle();
s = new SpannableString(title);
s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.devslopepos, null)), 0, s.length(), 0);
item.setTitle(s);
item.setCheckable(true);
item.setChecked(SP.getBoolean("showdevslope", false));
}
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
if (item.getItemId() == CHARTTYPE.PRE.ordinal()) {
SP.putBoolean("showprediction", !item.isChecked());
} else if (item.getItemId() == CHARTTYPE.BAS.ordinal()) {
SP.putBoolean("showbasals", !item.isChecked());
} else if (item.getItemId() == CHARTTYPE.IOB.ordinal()) {
SP.putBoolean("showiob", !item.isChecked());
} else if (item.getItemId() == CHARTTYPE.COB.ordinal()) {
SP.putBoolean("showcob", !item.isChecked());
} else if (item.getItemId() == CHARTTYPE.DEV.ordinal()) {
SP.putBoolean("showdeviations", !item.isChecked());
} else if (item.getItemId() == CHARTTYPE.SEN.ordinal()) {
SP.putBoolean("showratios", !item.isChecked());
} else if (item.getItemId() == CHARTTYPE.DEVSLOPE.ordinal()) {
SP.putBoolean("showdevslope", !item.isChecked());
}
scheduleUpdateGUI("onGraphCheckboxesCheckedChanged");
return true;
}
});
chartButton.setImageResource(R.drawable.ic_arrow_drop_up_white_24dp);
popup.setOnDismissListener(new PopupMenu.OnDismissListener() {
@Override
public void onDismiss(PopupMenu menu) {
chartButton.setImageResource(R.drawable.ic_arrow_drop_down_white_24dp);
}
});
popup.show();
} }
item = popup.getMenu().add(Menu.NONE, CHARTTYPE.BAS.ordinal(), Menu.NONE, MainApp.gs(R.string.overview_show_basals));
title = item.getTitle();
s = new SpannableString(title);
s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.basal, null)), 0, s.length(), 0);
item.setTitle(s);
item.setCheckable(true);
item.setChecked(SP.getBoolean("showbasals", true));
item = popup.getMenu().add(Menu.NONE, CHARTTYPE.IOB.ordinal(), Menu.NONE, MainApp.gs(R.string.overview_show_iob));
title = item.getTitle();
s = new SpannableString(title);
s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.iob, null)), 0, s.length(), 0);
item.setTitle(s);
item.setCheckable(true);
item.setChecked(SP.getBoolean("showiob", true));
item = popup.getMenu().add(Menu.NONE, CHARTTYPE.COB.ordinal(), Menu.NONE, MainApp.gs(R.string.overview_show_cob));
title = item.getTitle();
s = new SpannableString(title);
s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.cob, null)), 0, s.length(), 0);
item.setTitle(s);
item.setCheckable(true);
item.setChecked(SP.getBoolean("showcob", true));
item = popup.getMenu().add(Menu.NONE, CHARTTYPE.DEV.ordinal(), Menu.NONE, MainApp.gs(R.string.overview_show_deviations));
title = item.getTitle();
s = new SpannableString(title);
s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.deviations, null)), 0, s.length(), 0);
item.setTitle(s);
item.setCheckable(true);
item.setChecked(SP.getBoolean("showdeviations", false));
item = popup.getMenu().add(Menu.NONE, CHARTTYPE.SEN.ordinal(), Menu.NONE, MainApp.gs(R.string.overview_show_sensitivity));
title = item.getTitle();
s = new SpannableString(title);
s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.ratio, null)), 0, s.length(), 0);
item.setTitle(s);
item.setCheckable(true);
item.setChecked(SP.getBoolean("showratios", false));
if (MainApp.devBranch) {
item = popup.getMenu().add(Menu.NONE, CHARTTYPE.DEVSLOPE.ordinal(), Menu.NONE, "Deviation slope");
title = item.getTitle();
s = new SpannableString(title);
s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.devslopepos, null)), 0, s.length(), 0);
item.setTitle(s);
item.setCheckable(true);
item.setChecked(SP.getBoolean("showdevslope", false));
}
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
if (item.getItemId() == CHARTTYPE.PRE.ordinal()) {
SP.putBoolean("showprediction", !item.isChecked());
} else if (item.getItemId() == CHARTTYPE.BAS.ordinal()) {
SP.putBoolean("showbasals", !item.isChecked());
} else if (item.getItemId() == CHARTTYPE.IOB.ordinal()) {
SP.putBoolean("showiob", !item.isChecked());
} else if (item.getItemId() == CHARTTYPE.COB.ordinal()) {
SP.putBoolean("showcob", !item.isChecked());
} else if (item.getItemId() == CHARTTYPE.DEV.ordinal()) {
SP.putBoolean("showdeviations", !item.isChecked());
} else if (item.getItemId() == CHARTTYPE.SEN.ordinal()) {
SP.putBoolean("showratios", !item.isChecked());
} else if (item.getItemId() == CHARTTYPE.DEVSLOPE.ordinal()) {
SP.putBoolean("showdevslope", !item.isChecked());
}
scheduleUpdateGUI("onGraphCheckboxesCheckedChanged");
return true;
}
});
chartButton.setImageResource(R.drawable.ic_arrow_drop_up_white_24dp);
popup.setOnDismissListener(new PopupMenu.OnDismissListener() {
@Override
public void onDismiss(PopupMenu menu) {
chartButton.setImageResource(R.drawable.ic_arrow_drop_down_white_24dp);
}
});
popup.show();
}); });
} }
@ -638,8 +629,8 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
@Override @Override
public void onClick(View v) { public void onClick(View v) {
boolean xdrip = MainApp.getSpecificPlugin(SourceXdripPlugin.class) != null && MainApp.getSpecificPlugin(SourceXdripPlugin.class).isEnabled(PluginType.BGSOURCE); boolean xdrip = SourceXdripPlugin.getPlugin().isEnabled(PluginType.BGSOURCE);
boolean g5 = MainApp.getSpecificPlugin(SourceDexcomG5Plugin.class) != null && MainApp.getSpecificPlugin(SourceDexcomG5Plugin.class).isEnabled(PluginType.BGSOURCE); boolean g5 = SourceDexcomG5Plugin.getPlugin().isEnabled(PluginType.BGSOURCE);
String units = ProfileFunctions.getInstance().getProfileUnits(); String units = ProfileFunctions.getInstance().getProfileUnits();
FragmentManager manager = getFragmentManager(); FragmentManager manager = getFragmentManager();
@ -1027,7 +1018,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
public void updateGUI(final String from) { public void updateGUI(final String from) {
if (L.isEnabled(L.OVERVIEW)) if (L.isEnabled(L.OVERVIEW))
log.debug("updateGUI entered from: " + from); log.debug("updateGUI entered from: " + from);
final Date updateGUIStart = new Date(); final long updateGUIStart = System.currentTimeMillis();
if (getActivity() == null) if (getActivity() == null)
return; return;
@ -1367,7 +1358,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
// Uploader status from ns // Uploader status from ns
if (uploaderDeviceStatusView != null) { if (uploaderDeviceStatusView != null) {
uploaderDeviceStatusView.setText(NSDeviceStatus.getInstance().getUploaderStatus()); uploaderDeviceStatusView.setText(NSDeviceStatus.getInstance().getUploaderStatusSpanned());
uploaderDeviceStatusView.setOnClickListener(v -> OKDialog.show(getActivity(), MainApp.gs(R.string.uploader), NSDeviceStatus.getInstance().getExtendedUploaderStatus(), null)); uploaderDeviceStatusView.setOnClickListener(v -> OKDialog.show(getActivity(), MainApp.gs(R.string.uploader), NSDeviceStatus.getInstance().getExtendedUploaderStatus(), null));
} }

View file

@ -250,6 +250,15 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint
return false; return false;
} }
@Override
public boolean isHandshakeInProgress() {
return false;
}
@Override
public void finishHandshaking() {
}
@Override @Override
public void connect(String reason) { public void connect(String reason) {
// ruffyscripter establishes a connection as needed. // ruffyscripter establishes a connection as needed.
@ -355,8 +364,8 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint
@NonNull @NonNull
@Override @Override
public Date lastDataTime() { public long lastDataTime() {
return new Date(pump.lastSuccessfulCmdTime); return pump.lastSuccessfulCmdTime;
} }
/** /**

View file

@ -143,8 +143,8 @@ public abstract class AbstractDanaRPlugin extends PluginBase implements PumpInte
} }
@Override @Override
public Date lastDataTime() { public long lastDataTime() {
return new Date(DanaRPump.getInstance().lastConnection); return DanaRPump.getInstance().lastConnection;
} }
@Override @Override
@ -333,8 +333,8 @@ public abstract class AbstractDanaRPlugin extends PluginBase implements PumpInte
status.put("timestamp", DateUtil.toISOString(pump.lastConnection)); status.put("timestamp", DateUtil.toISOString(pump.lastConnection));
extended.put("Version", BuildConfig.VERSION_NAME + "-" + BuildConfig.BUILDVERSION); extended.put("Version", BuildConfig.VERSION_NAME + "-" + BuildConfig.BUILDVERSION);
extended.put("PumpIOB", pump.iob); extended.put("PumpIOB", pump.iob);
if (pump.lastBolusTime.getTime() != 0) { if (pump.lastBolusTime != 0) {
extended.put("LastBolus", pump.lastBolusTime.toLocaleString()); extended.put("LastBolus", DateUtil.dateAndTimeFullString(pump.lastBolusTime));
extended.put("LastBolusAmount", pump.lastBolusAmount); extended.put("LastBolusAmount", pump.lastBolusAmount);
} }
TemporaryBasal tb = TreatmentsPlugin.getPlugin().getRealTempBasalFromHistory(now); TemporaryBasal tb = TreatmentsPlugin.getPlugin().getRealTempBasalFromHistory(now);
@ -441,7 +441,7 @@ public abstract class AbstractDanaRPlugin extends PluginBase implements PumpInte
int agoMin = (int) (agoMsec / 60d / 1000d); int agoMin = (int) (agoMsec / 60d / 1000d);
ret += "LastConn: " + agoMin + " minago\n"; ret += "LastConn: " + agoMin + " minago\n";
} }
if (pump.lastBolusTime.getTime() != 0) { if (pump.lastBolusTime != 0) {
ret += "LastBolus: " + DecimalFormatter.to2Decimal(pump.lastBolusAmount) + "U @" + android.text.format.DateFormat.format("HH:mm", pump.lastBolusTime) + "\n"; ret += "LastBolus: " + DecimalFormatter.to2Decimal(pump.lastBolusAmount) + "U @" + android.text.format.DateFormat.format("HH:mm", pump.lastBolusTime) + "\n";
} }
TemporaryBasal activeTemp = TreatmentsPlugin.getPlugin().getRealTempBasalFromHistory(System.currentTimeMillis()); TemporaryBasal activeTemp = TreatmentsPlugin.getPlugin().getRealTempBasalFromHistory(System.currentTimeMillis());

View file

@ -1,7 +1,6 @@
package info.nightscout.androidaps.plugins.PumpDanaR; package info.nightscout.androidaps.plugins.PumpDanaR;
import android.annotation.SuppressLint;
import android.app.Activity; import android.app.Activity;
import android.content.Intent; import android.content.Intent;
import android.os.Bundle; import android.os.Bundle;
@ -27,6 +26,7 @@ import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.activities.TDDStatsActivity; import info.nightscout.androidaps.activities.TDDStatsActivity;
import info.nightscout.androidaps.db.ExtendedBolus; import info.nightscout.androidaps.db.ExtendedBolus;
import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.events.EventExtendedBolusChange; import info.nightscout.androidaps.events.EventExtendedBolusChange;
import info.nightscout.androidaps.events.EventPumpStatusChanged; import info.nightscout.androidaps.events.EventPumpStatusChanged;
import info.nightscout.androidaps.events.EventTempBasalChange; import info.nightscout.androidaps.events.EventTempBasalChange;
@ -157,27 +157,24 @@ public class DanaRFragment extends SubscriberFragment {
final String status = c.textStatus(); final String status = c.textStatus();
if (activity != null) { if (activity != null) {
activity.runOnUiThread( activity.runOnUiThread(
new Runnable() { () -> {
@Override synchronized (DanaRFragment.this) {
public void run() {
synchronized (DanaRFragment.this) {
if (btConnectionView == null || pumpStatusView == null || pumpStatusLayout == null) if (btConnectionView == null || pumpStatusView == null || pumpStatusLayout == null)
return; return;
if (c.sStatus == EventPumpStatusChanged.CONNECTING) if (c.sStatus == EventPumpStatusChanged.CONNECTING)
btConnectionView.setText("{fa-bluetooth-b spin} " + c.sSecondsElapsed + "s"); btConnectionView.setText("{fa-bluetooth-b spin} " + c.sSecondsElapsed + "s");
else if (c.sStatus == EventPumpStatusChanged.CONNECTED) else if (c.sStatus == EventPumpStatusChanged.CONNECTED)
btConnectionView.setText("{fa-bluetooth}"); btConnectionView.setText("{fa-bluetooth}");
else if (c.sStatus == EventPumpStatusChanged.DISCONNECTED) else if (c.sStatus == EventPumpStatusChanged.DISCONNECTED)
btConnectionView.setText("{fa-bluetooth-b}"); btConnectionView.setText("{fa-bluetooth-b}");
if (!status.equals("")) { if (!status.equals("")) {
pumpStatusView.setText(status); pumpStatusView.setText(status);
pumpStatusLayout.setVisibility(View.VISIBLE); pumpStatusLayout.setVisibility(View.VISIBLE);
} else { } else {
pumpStatusLayout.setVisibility(View.GONE); pumpStatusLayout.setVisibility(View.GONE);
}
} }
} }
} }
@ -210,80 +207,77 @@ public class DanaRFragment extends SubscriberFragment {
protected void updateGUI() { protected void updateGUI() {
Activity activity = getActivity(); Activity activity = getActivity();
if (activity != null && basaBasalRateView != null) if (activity != null && basaBasalRateView != null)
activity.runOnUiThread(new Runnable() { activity.runOnUiThread(() -> {
@SuppressLint("SetTextI18n") synchronized (DanaRFragment.this) {
@Override if (!isBound()) return;
public void run() {
synchronized (DanaRFragment.this) {
if (!isBound()) return;
DanaRPump pump = DanaRPump.getInstance(); DanaRPump pump = DanaRPump.getInstance();
if (pump.lastConnection != 0) { if (pump.lastConnection != 0) {
Long agoMsec = System.currentTimeMillis() - pump.lastConnection; Long agoMsec = System.currentTimeMillis() - pump.lastConnection;
int agoMin = (int) (agoMsec / 60d / 1000d); int agoMin = (int) (agoMsec / 60d / 1000d);
lastConnectionView.setText(DateUtil.timeString(pump.lastConnection) + " (" + String.format(MainApp.gs(R.string.minago), agoMin) + ")"); lastConnectionView.setText(DateUtil.timeString(pump.lastConnection) + " (" + String.format(MainApp.gs(R.string.minago), agoMin) + ")");
SetWarnColor.setColor(lastConnectionView, agoMin, 16d, 31d); SetWarnColor.setColor(lastConnectionView, agoMin, 16d, 31d);
} }
if (pump.lastBolusTime.getTime() != 0) { if (pump.lastBolusTime != 0) {
Long agoMsec = System.currentTimeMillis() - pump.lastBolusTime.getTime(); Long agoMsec = System.currentTimeMillis() - pump.lastBolusTime;
double agoHours = agoMsec / 60d / 60d / 1000d; double agoHours = agoMsec / 60d / 60d / 1000d;
if (agoHours < 6) // max 6h back if (agoHours < 6) // max 6h back
lastBolusView.setText(DateUtil.timeString(pump.lastBolusTime) + " " + DateUtil.sinceString(pump.lastBolusTime.getTime()) + " " + DecimalFormatter.to2Decimal(DanaRPump.getInstance().lastBolusAmount) + " U"); lastBolusView.setText(DateUtil.timeString(pump.lastBolusTime) + " " + DateUtil.sinceString(pump.lastBolusTime) + " " + DecimalFormatter.to2Decimal(DanaRPump.getInstance().lastBolusAmount) + " U");
else lastBolusView.setText(""); else lastBolusView.setText("");
} }
dailyUnitsView.setText(DecimalFormatter.to0Decimal(pump.dailyTotalUnits) + " / " + pump.maxDailyTotalUnits + " U"); dailyUnitsView.setText(DecimalFormatter.to0Decimal(pump.dailyTotalUnits) + " / " + pump.maxDailyTotalUnits + " U");
SetWarnColor.setColor(dailyUnitsView, pump.dailyTotalUnits, pump.maxDailyTotalUnits * 0.75d, pump.maxDailyTotalUnits * 0.9d); SetWarnColor.setColor(dailyUnitsView, pump.dailyTotalUnits, pump.maxDailyTotalUnits * 0.75d, pump.maxDailyTotalUnits * 0.9d);
basaBasalRateView.setText("( " + (pump.activeProfile + 1) + " ) " + DecimalFormatter.to2Decimal(ConfigBuilderPlugin.getActivePump().getBaseBasalRate()) + " U/h"); basaBasalRateView.setText("( " + (pump.activeProfile + 1) + " ) " + DecimalFormatter.to2Decimal(ConfigBuilderPlugin.getActivePump().getBaseBasalRate()) + " U/h");
// DanaRPlugin, DanaRKoreanPlugin // DanaRPlugin, DanaRKoreanPlugin
if (ConfigBuilderPlugin.getActivePump().isFakingTempsByExtendedBoluses()) { if (ConfigBuilderPlugin.getActivePump().isFakingTempsByExtendedBoluses()) {
if (TreatmentsPlugin.getPlugin().isInHistoryRealTempBasalInProgress()) { if (TreatmentsPlugin.getPlugin().isInHistoryRealTempBasalInProgress()) {
tempBasalView.setText(TreatmentsPlugin.getPlugin().getRealTempBasalFromHistory(System.currentTimeMillis()).toStringFull()); tempBasalView.setText(TreatmentsPlugin.getPlugin().getRealTempBasalFromHistory(System.currentTimeMillis()).toStringFull());
} else {
tempBasalView.setText("");
}
} else { } else {
// v2 plugin tempBasalView.setText("");
if (TreatmentsPlugin.getPlugin().isTempBasalInProgress()) {
tempBasalView.setText(TreatmentsPlugin.getPlugin().getTempBasalFromHistory(System.currentTimeMillis()).toStringFull());
} else {
tempBasalView.setText("");
}
} }
ExtendedBolus activeExtendedBolus = TreatmentsPlugin.getPlugin().getExtendedBolusFromHistory(System.currentTimeMillis()); } else {
if (activeExtendedBolus != null) { // v2 plugin
extendedBolusView.setText(activeExtendedBolus.toString()); TemporaryBasal tb = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(System.currentTimeMillis());
if (tb != null) {
tempBasalView.setText(tb.toStringFull());
} else { } else {
extendedBolusView.setText(""); tempBasalView.setText("");
} }
reservoirView.setText(DecimalFormatter.to0Decimal(pump.reservoirRemainingUnits) + " / 300 U"); }
SetWarnColor.setColorInverse(reservoirView, pump.reservoirRemainingUnits, 50d, 20d); ExtendedBolus activeExtendedBolus = TreatmentsPlugin.getPlugin().getExtendedBolusFromHistory(System.currentTimeMillis());
batteryView.setText("{fa-battery-" + (pump.batteryRemaining / 25) + "}"); if (activeExtendedBolus != null) {
SetWarnColor.setColorInverse(batteryView, pump.batteryRemaining, 51d, 26d); extendedBolusView.setText(activeExtendedBolus.toString());
iobView.setText(pump.iob + " U"); } else {
if (pump.model != 0 || pump.protocol != 0 || pump.productCode != 0) { extendedBolusView.setText("");
firmwareView.setText(String.format(MainApp.gs(R.string.danar_model), pump.model, pump.protocol, pump.productCode)); }
reservoirView.setText(DecimalFormatter.to0Decimal(pump.reservoirRemainingUnits) + " / 300 U");
SetWarnColor.setColorInverse(reservoirView, pump.reservoirRemainingUnits, 50d, 20d);
batteryView.setText("{fa-battery-" + (pump.batteryRemaining / 25) + "}");
SetWarnColor.setColorInverse(batteryView, pump.batteryRemaining, 51d, 26d);
iobView.setText(pump.iob + " U");
if (pump.model != 0 || pump.protocol != 0 || pump.productCode != 0) {
firmwareView.setText(String.format(MainApp.gs(R.string.danar_model), pump.model, pump.protocol, pump.productCode));
} else {
firmwareView.setText("OLD");
}
basalStepView.setText("" + pump.basalStep);
bolusStepView.setText("" + pump.bolusStep);
serialNumberView.setText("" + pump.serialNumber);
if (queueView != null) {
Spanned status = ConfigBuilderPlugin.getCommandQueue().spannedStatus();
if (status.toString().equals("")) {
queueView.setVisibility(View.GONE);
} else { } else {
firmwareView.setText("OLD"); queueView.setVisibility(View.VISIBLE);
} queueView.setText(status);
basalStepView.setText("" + pump.basalStep);
bolusStepView.setText("" + pump.bolusStep);
serialNumberView.setText("" + pump.serialNumber);
if (queueView != null) {
Spanned status = ConfigBuilderPlugin.getCommandQueue().spannedStatus();
if (status.toString().equals("")) {
queueView.setVisibility(View.GONE);
} else {
queueView.setVisibility(View.VISIBLE);
queueView.setText(status);
}
}
//hide user options button if not an RS pump
boolean isKorean = MainApp.getSpecificPlugin(DanaRKoreanPlugin.class) != null && MainApp.getSpecificPlugin(DanaRKoreanPlugin.class).isEnabled(PluginType.PUMP);
if (isKorean) {
danar_user_options.setVisibility(View.GONE);
} }
} }
//hide user options button if not an RS pump
boolean isKorean = DanaRKoreanPlugin.getPlugin().isEnabled(PluginType.PUMP);
if (isKorean) {
danar_user_options.setVisibility(View.GONE);
}
} }
}); });
} }

View file

@ -175,6 +175,16 @@ public class DanaRPlugin extends AbstractDanaRPlugin {
return pump.lastConnection > 0 && pump.isExtendedBolusEnabled && pump.maxBasal > 0; return pump.lastConnection > 0 && pump.isExtendedBolusEnabled && pump.maxBasal > 0;
} }
@Override
public boolean isHandshakeInProgress() {
return sExecutionService != null && sExecutionService.isHandshakeInProgress();
}
@Override
public void finishHandshaking() {
sExecutionService.finishHandshaking();
}
@Override @Override
public PumpEnactResult deliverTreatment(DetailedBolusInfo detailedBolusInfo) { public PumpEnactResult deliverTreatment(DetailedBolusInfo detailedBolusInfo) {
detailedBolusInfo.insulin = MainApp.getConstraintChecker().applyBolusConstraints(new Constraint<>(detailedBolusInfo.insulin)).value(); detailedBolusInfo.insulin = MainApp.getConstraintChecker().applyBolusConstraints(new Constraint<>(detailedBolusInfo.insulin)).value();

View file

@ -65,11 +65,11 @@ public class DanaRPump {
// Info // Info
public String serialNumber = ""; public String serialNumber = "";
public Date shippingDate = new Date(0); public long shippingDate = 0;
public String shippingCountry = ""; public String shippingCountry = "";
public boolean isNewPump = true; public boolean isNewPump = true;
public int password = -1; public int password = -1;
public Date pumpTime = new Date(0); public long pumpTime = 0;
public static final int DOMESTIC_MODEL = 0x01; public static final int DOMESTIC_MODEL = 0x01;
public static final int EXPORT_MODEL = 0x03; public static final int EXPORT_MODEL = 0x03;
@ -98,7 +98,7 @@ public class DanaRPump {
public int batteryRemaining; public int batteryRemaining;
public boolean bolusBlocked; public boolean bolusBlocked;
public Date lastBolusTime = new Date(0); public long lastBolusTime = 0;
public double lastBolusAmount; public double lastBolusAmount;
public double currentBasal; public double currentBasal;
@ -107,7 +107,7 @@ public class DanaRPump {
public int tempBasalPercent; public int tempBasalPercent;
public int tempBasalRemainingMin; public int tempBasalRemainingMin;
public int tempBasalTotalSec; public int tempBasalTotalSec;
public Date tempBasalStart; public long tempBasalStart;
public boolean isDualBolusInProgress; public boolean isDualBolusInProgress;
public boolean isExtendedInProgress; public boolean isExtendedInProgress;
@ -115,7 +115,7 @@ public class DanaRPump {
public double extendedBolusAmount; public double extendedBolusAmount;
public double extendedBolusAbsoluteRate; public double extendedBolusAbsoluteRate;
public int extendedBolusSoFarInMinutes; public int extendedBolusSoFarInMinutes;
public Date extendedBolusStart; public long extendedBolusStart;
public int extendedBolusRemainingMinutes; public int extendedBolusRemainingMinutes;
public double extendedBolusDeliveredSoFar; //RS only public double extendedBolusDeliveredSoFar; //RS only

View file

@ -1,8 +1,6 @@
package info.nightscout.androidaps.plugins.PumpDanaR.Dialogs; package info.nightscout.androidaps.plugins.PumpDanaR.Dialogs;
import android.os.Bundle; import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.support.v4.app.DialogFragment; import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.View; import android.view.View;
@ -10,22 +8,12 @@ import android.view.ViewGroup;
import android.widget.Button; import android.widget.Button;
import android.widget.TextView; import android.widget.TextView;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.ProfileStore;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.data.ProfileStore;
import info.nightscout.androidaps.interfaces.ProfileInterface; import info.nightscout.androidaps.interfaces.ProfileInterface;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPlugin;
import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump;
import info.nightscout.androidaps.plugins.PumpDanaRKorean.DanaRKoreanPlugin;
import info.nightscout.androidaps.plugins.PumpDanaRv2.DanaRv2Plugin;
import info.nightscout.androidaps.plugins.Treatments.fragments.ProfileGraph; import info.nightscout.androidaps.plugins.Treatments.fragments.ProfileGraph;
import info.nightscout.utils.DecimalFormatter; import info.nightscout.utils.DecimalFormatter;

View file

@ -129,8 +129,8 @@ public class MessageBase {
return 0; return 0;
} }
public static Date dateTimeFromBuff(byte[] buff, int offset) { public static long dateTimeFromBuff(byte[] buff, int offset) {
Date date = return
new Date( new Date(
100 + intFromBuff(buff, offset, 1), 100 + intFromBuff(buff, offset, 1),
intFromBuff(buff, offset + 1, 1) - 1, intFromBuff(buff, offset + 1, 1) - 1,
@ -138,12 +138,11 @@ public class MessageBase {
intFromBuff(buff, offset + 3, 1), intFromBuff(buff, offset + 3, 1),
intFromBuff(buff, offset + 4, 1), intFromBuff(buff, offset + 4, 1),
0 0
); ).getTime();
return date;
} }
public static Date dateTimeSecFromBuff(byte[] buff, int offset) { public static synchronized long dateTimeSecFromBuff(byte[] buff, int offset) {
Date date = return
new Date( new Date(
100 + intFromBuff(buff, offset, 1), 100 + intFromBuff(buff, offset, 1),
intFromBuff(buff, offset + 1, 1) - 1, intFromBuff(buff, offset + 1, 1) - 1,
@ -151,18 +150,16 @@ public class MessageBase {
intFromBuff(buff, offset + 3, 1), intFromBuff(buff, offset + 3, 1),
intFromBuff(buff, offset + 4, 1), intFromBuff(buff, offset + 4, 1),
intFromBuff(buff, offset + 5, 1) intFromBuff(buff, offset + 5, 1)
); ).getTime();
return date;
} }
public static Date dateFromBuff(byte[] buff, int offset) { public static long dateFromBuff(byte[] buff, int offset) {
Date date = return
new Date( new Date(
100 + intFromBuff(buff, offset, 1), 100 + intFromBuff(buff, offset, 1),
intFromBuff(buff, offset + 1, 1) - 1, intFromBuff(buff, offset + 1, 1) - 1,
intFromBuff(buff, offset + 2, 1) intFromBuff(buff, offset + 2, 1)
); ).getTime();
return date;
} }
@TargetApi(Build.VERSION_CODES.KITKAT) @TargetApi(Build.VERSION_CODES.KITKAT)

View file

@ -23,9 +23,9 @@ public class MsgHistoryAll extends MessageBase {
@Override @Override
public void handleMessage(byte[] bytes) { public void handleMessage(byte[] bytes) {
byte recordCode = (byte) intFromBuff(bytes, 0, 1); byte recordCode = (byte) intFromBuff(bytes, 0, 1);
Date date = dateFromBuff(bytes, 1); // 3 bytes long date = dateFromBuff(bytes, 1); // 3 bytes
Date datetime = dateTimeFromBuff(bytes, 1); // 5 bytes long datetime = dateTimeFromBuff(bytes, 1); // 5 bytes
Date datetimewihtsec = dateTimeSecFromBuff(bytes, 1); // 6 bytes long datetimewihtsec = dateTimeSecFromBuff(bytes, 1); // 6 bytes
double dailyBasal = intFromBuff(bytes, 4, 2) * 0.01d; double dailyBasal = intFromBuff(bytes, 4, 2) * 0.01d;
double dailyBolus = intFromBuff(bytes, 6, 2) * 0.01d; double dailyBolus = intFromBuff(bytes, 6, 2) * 0.01d;
@ -46,7 +46,7 @@ public class MsgHistoryAll extends MessageBase {
switch (recordCode) { switch (recordCode) {
case RecordTypes.RECORD_TYPE_BOLUS: case RecordTypes.RECORD_TYPE_BOLUS:
danaRHistoryRecord.recordDate = datetime.getTime(); danaRHistoryRecord.recordDate = datetime;
switch (0xF0 & paramByte8) { switch (0xF0 & paramByte8) {
case 0xA0: case 0xA0:
danaRHistoryRecord.bolusType = "DS"; danaRHistoryRecord.bolusType = "DS";
@ -73,48 +73,48 @@ public class MsgHistoryAll extends MessageBase {
break; break;
case RecordTypes.RECORD_TYPE_DAILY: case RecordTypes.RECORD_TYPE_DAILY:
messageType += "dailyinsulin"; messageType += "dailyinsulin";
danaRHistoryRecord.recordDate = date.getTime(); danaRHistoryRecord.recordDate = date;
danaRHistoryRecord.recordDailyBasal = dailyBasal; danaRHistoryRecord.recordDailyBasal = dailyBasal;
danaRHistoryRecord.recordDailyBolus = dailyBolus; danaRHistoryRecord.recordDailyBolus = dailyBolus;
break; break;
case RecordTypes.RECORD_TYPE_PRIME: case RecordTypes.RECORD_TYPE_PRIME:
messageType += "prime"; messageType += "prime";
danaRHistoryRecord.recordDate = datetimewihtsec.getTime(); danaRHistoryRecord.recordDate = datetimewihtsec;
danaRHistoryRecord.recordValue = value * 0.01; danaRHistoryRecord.recordValue = value * 0.01;
break; break;
case RecordTypes.RECORD_TYPE_ERROR: case RecordTypes.RECORD_TYPE_ERROR:
messageType += "error"; messageType += "error";
danaRHistoryRecord.recordDate = datetimewihtsec.getTime(); danaRHistoryRecord.recordDate = datetimewihtsec;
danaRHistoryRecord.recordValue = value * 0.01; danaRHistoryRecord.recordValue = value * 0.01;
break; break;
case RecordTypes.RECORD_TYPE_REFILL: case RecordTypes.RECORD_TYPE_REFILL:
messageType += "refill"; messageType += "refill";
danaRHistoryRecord.recordDate = datetimewihtsec.getTime(); danaRHistoryRecord.recordDate = datetimewihtsec;
danaRHistoryRecord.recordValue = value * 0.01; danaRHistoryRecord.recordValue = value * 0.01;
break; break;
case RecordTypes.RECORD_TYPE_BASALHOUR: case RecordTypes.RECORD_TYPE_BASALHOUR:
messageType += "basal hour"; messageType += "basal hour";
danaRHistoryRecord.recordDate = datetimewihtsec.getTime(); danaRHistoryRecord.recordDate = datetimewihtsec;
danaRHistoryRecord.recordValue = value * 0.01; danaRHistoryRecord.recordValue = value * 0.01;
break; break;
case RecordTypes.RECORD_TYPE_TB: case RecordTypes.RECORD_TYPE_TB:
messageType += "tb"; messageType += "tb";
danaRHistoryRecord.recordDate = datetimewihtsec.getTime(); danaRHistoryRecord.recordDate = datetimewihtsec;
danaRHistoryRecord.recordValue = value * 0.01; danaRHistoryRecord.recordValue = value * 0.01;
break; break;
case RecordTypes.RECORD_TYPE_GLUCOSE: case RecordTypes.RECORD_TYPE_GLUCOSE:
messageType += "glucose"; messageType += "glucose";
danaRHistoryRecord.recordDate = datetimewihtsec.getTime(); danaRHistoryRecord.recordDate = datetimewihtsec;
danaRHistoryRecord.recordValue = value; danaRHistoryRecord.recordValue = value;
break; break;
case RecordTypes.RECORD_TYPE_CARBO: case RecordTypes.RECORD_TYPE_CARBO:
messageType += "carbo"; messageType += "carbo";
danaRHistoryRecord.recordDate = datetimewihtsec.getTime(); danaRHistoryRecord.recordDate = datetimewihtsec;
danaRHistoryRecord.recordValue = value; danaRHistoryRecord.recordValue = value;
break; break;
case RecordTypes.RECORD_TYPE_ALARM: case RecordTypes.RECORD_TYPE_ALARM:
messageType += "alarm"; messageType += "alarm";
danaRHistoryRecord.recordDate = datetimewihtsec.getTime(); danaRHistoryRecord.recordDate = datetimewihtsec;
String strAlarm = "None"; String strAlarm = "None";
switch ((int) paramByte8) { switch ((int) paramByte8) {
case 67: case 67:
@ -135,7 +135,7 @@ public class MsgHistoryAll extends MessageBase {
break; break;
case RecordTypes.RECORD_TYPE_SUSPEND: case RecordTypes.RECORD_TYPE_SUSPEND:
messageType += "suspend"; messageType += "suspend";
danaRHistoryRecord.recordDate = datetimewihtsec.getTime(); danaRHistoryRecord.recordDate = datetimewihtsec;
String strRecordValue = "Off"; String strRecordValue = "Off";
if ((int) paramByte8 == 79) if ((int) paramByte8 == 79)
strRecordValue = "On"; strRecordValue = "On";

View file

@ -4,6 +4,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump; import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump;
/** /**
@ -34,6 +35,9 @@ public class MsgInitConnStatusOption extends MessageBase {
if (L.isEnabled(L.PUMPCOMM)) if (L.isEnabled(L.PUMPCOMM))
log.debug("Pump password: " + DanaRPump.getInstance().password); log.debug("Pump password: " + DanaRPump.getInstance().password);
} }
// This is last message of initial sequence
ConfigBuilderPlugin.getPlugin().getActivePump().finishHandshaking();
} }
} }

View file

@ -16,6 +16,7 @@ import info.nightscout.androidaps.plugins.Overview.notifications.Notification;
import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPlugin; import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPlugin;
import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump; import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump;
import info.nightscout.androidaps.plugins.PumpDanaRKorean.DanaRKoreanPlugin; import info.nightscout.androidaps.plugins.PumpDanaRKorean.DanaRKoreanPlugin;
import info.nightscout.utils.DateUtil;
public class MsgInitConnStatusTime extends MessageBase { public class MsgInitConnStatusTime extends MessageBase {
private static Logger log = LoggerFactory.getLogger(L.PUMPCOMM); private static Logger log = LoggerFactory.getLogger(L.PUMPCOMM);
@ -52,11 +53,11 @@ public class MsgInitConnStatusTime extends MessageBase {
return; return;
} }
Date time = dateTimeSecFromBuff(bytes, 0); long time = dateTimeSecFromBuff(bytes, 0);
int versionCode = intFromBuff(bytes, 6, 1); int versionCode = intFromBuff(bytes, 6, 1);
if (L.isEnabled(L.PUMPCOMM)) { if (L.isEnabled(L.PUMPCOMM)) {
log.debug("Pump time: " + time); log.debug("Pump time: " + DateUtil.dateAndTimeFullString(time));
log.debug("Version code: " + versionCode); log.debug("Version code: " + versionCode);
} }
} }

View file

@ -7,6 +7,7 @@ import java.util.Date;
import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump; import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump;
import info.nightscout.utils.DateUtil;
public class MsgSettingPumpTime extends MessageBase { public class MsgSettingPumpTime extends MessageBase {
private static Logger log = LoggerFactory.getLogger(L.PUMPCOMM); private static Logger log = LoggerFactory.getLogger(L.PUMPCOMM);
@ -18,7 +19,7 @@ public class MsgSettingPumpTime extends MessageBase {
} }
public void handleMessage(byte[] bytes) { public void handleMessage(byte[] bytes) {
Date time = long time =
new Date( new Date(
100 + intFromBuff(bytes, 5, 1), 100 + intFromBuff(bytes, 5, 1),
intFromBuff(bytes, 4, 1) - 1, intFromBuff(bytes, 4, 1) - 1,
@ -26,10 +27,10 @@ public class MsgSettingPumpTime extends MessageBase {
intFromBuff(bytes, 2, 1), intFromBuff(bytes, 2, 1),
intFromBuff(bytes, 1, 1), intFromBuff(bytes, 1, 1),
intFromBuff(bytes, 0, 1) intFromBuff(bytes, 0, 1)
); ).getTime();
if (L.isEnabled(L.PUMPCOMM)) if (L.isEnabled(L.PUMPCOMM))
log.debug("Pump time: " + time + " Phone time: " + new Date()); log.debug("Pump time: " + DateUtil.dateAndTimeFullString(time) + " Phone time: " + new Date());
DanaRPump.getInstance().pumpTime = time; DanaRPump.getInstance().pumpTime = time;
} }

View file

@ -5,14 +5,13 @@ import android.support.annotation.NonNull;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.Date;
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.interfaces.TreatmentsInterface; import info.nightscout.androidaps.interfaces.TreatmentsInterface;
import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump; import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump;
import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin; import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin;
import info.nightscout.utils.DateUtil;
public class MsgStatusBolusExtended extends MessageBase { public class MsgStatusBolusExtended extends MessageBase {
private static Logger log = LoggerFactory.getLogger(L.PUMPCOMM); private static Logger log = LoggerFactory.getLogger(L.PUMPCOMM);
@ -36,7 +35,7 @@ public class MsgStatusBolusExtended extends MessageBase {
int extendedBolusSoFarInMinutes = extendedBolusSoFarInSecs / 60; int extendedBolusSoFarInMinutes = extendedBolusSoFarInSecs / 60;
double extendedBolusAbsoluteRate = isExtendedInProgress ? extendedBolusAmount / extendedBolusMinutes * 60 : 0d; double extendedBolusAbsoluteRate = isExtendedInProgress ? extendedBolusAmount / extendedBolusMinutes * 60 : 0d;
Date extendedBolusStart = isExtendedInProgress ? getDateFromSecAgo(extendedBolusSoFarInSecs) : new Date(0); long extendedBolusStart = isExtendedInProgress ? getDateFromSecAgo(extendedBolusSoFarInSecs) : 0;
int extendedBolusRemainingMinutes = extendedBolusMinutes - extendedBolusSoFarInMinutes; int extendedBolusRemainingMinutes = extendedBolusMinutes - extendedBolusSoFarInMinutes;
DanaRPump pump = DanaRPump.getInstance(); DanaRPump pump = DanaRPump.getInstance();
@ -56,14 +55,14 @@ public class MsgStatusBolusExtended extends MessageBase {
log.debug("Extended bolus amount: " + extendedBolusAmount); log.debug("Extended bolus amount: " + extendedBolusAmount);
log.debug("Extended bolus so far in minutes: " + extendedBolusSoFarInMinutes); log.debug("Extended bolus so far in minutes: " + extendedBolusSoFarInMinutes);
log.debug("Extended bolus absolute rate: " + extendedBolusAbsoluteRate); log.debug("Extended bolus absolute rate: " + extendedBolusAbsoluteRate);
log.debug("Extended bolus start: " + extendedBolusStart); log.debug("Extended bolus start: " + DateUtil.dateAndTimeFullString(extendedBolusStart));
log.debug("Extended bolus remaining minutes: " + extendedBolusRemainingMinutes); log.debug("Extended bolus remaining minutes: " + extendedBolusRemainingMinutes);
} }
} }
@NonNull @NonNull
private Date getDateFromSecAgo(int tempBasalAgoSecs) { private long getDateFromSecAgo(int tempBasalAgoSecs) {
return new Date((long) (Math.ceil(System.currentTimeMillis() / 1000d) - tempBasalAgoSecs) * 1000); return (long) (Math.ceil(System.currentTimeMillis() / 1000d) - tempBasalAgoSecs) * 1000;
} }
public static void updateExtendedBolusInDB() { public static void updateExtendedBolusInDB() {
@ -76,12 +75,12 @@ public class MsgStatusBolusExtended extends MessageBase {
if (pump.isExtendedInProgress) { if (pump.isExtendedInProgress) {
if (extendedBolus.absoluteRate() != pump.extendedBolusAbsoluteRate) { if (extendedBolus.absoluteRate() != pump.extendedBolusAbsoluteRate) {
// Close current extended // Close current extended
ExtendedBolus exStop = new ExtendedBolus(pump.extendedBolusStart.getTime() - 1000); ExtendedBolus exStop = new ExtendedBolus(pump.extendedBolusStart - 1000);
exStop.source = Source.USER; exStop.source = Source.USER;
treatmentsInterface.addToHistoryExtendedBolus(exStop); treatmentsInterface.addToHistoryExtendedBolus(exStop);
// Create new // Create new
ExtendedBolus newExtended = new ExtendedBolus(); ExtendedBolus newExtended = new ExtendedBolus();
newExtended.date = pump.extendedBolusStart.getTime(); newExtended.date = pump.extendedBolusStart;
newExtended.insulin = pump.extendedBolusAmount; newExtended.insulin = pump.extendedBolusAmount;
newExtended.durationInMinutes = pump.extendedBolusMinutes; newExtended.durationInMinutes = pump.extendedBolusMinutes;
newExtended.source = Source.USER; newExtended.source = Source.USER;
@ -97,7 +96,7 @@ public class MsgStatusBolusExtended extends MessageBase {
if (pump.isExtendedInProgress) { if (pump.isExtendedInProgress) {
// Create new // Create new
ExtendedBolus newExtended = new ExtendedBolus(); ExtendedBolus newExtended = new ExtendedBolus();
newExtended.date = pump.extendedBolusStart.getTime(); newExtended.date = pump.extendedBolusStart;
newExtended.insulin = pump.extendedBolusAmount; newExtended.insulin = pump.extendedBolusAmount;
newExtended.durationInMinutes = pump.extendedBolusMinutes; newExtended.durationInMinutes = pump.extendedBolusMinutes;
newExtended.source = Source.USER; newExtended.source = Source.USER;

View file

@ -5,8 +5,6 @@ import android.support.annotation.NonNull;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.Date;
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.logging.L;
@ -33,7 +31,7 @@ public class MsgStatusTempBasal extends MessageBase {
else tempBasalTotalSec = intFromBuff(bytes, 2, 1) * 60 * 60; else tempBasalTotalSec = intFromBuff(bytes, 2, 1) * 60 * 60;
int tempBasalRunningSeconds = intFromBuff(bytes, 3, 3); int tempBasalRunningSeconds = intFromBuff(bytes, 3, 3);
int tempBasalRemainingMin = (tempBasalTotalSec - tempBasalRunningSeconds) / 60; int tempBasalRemainingMin = (tempBasalTotalSec - tempBasalRunningSeconds) / 60;
Date tempBasalStart = isTempBasalInProgress ? getDateFromTempBasalSecAgo(tempBasalRunningSeconds) : new Date(0); long tempBasalStart = isTempBasalInProgress ? getDateFromTempBasalSecAgo(tempBasalRunningSeconds) : 0;
DanaRPump pump = DanaRPump.getInstance(); DanaRPump pump = DanaRPump.getInstance();
pump.isTempBasalInProgress = isTempBasalInProgress; pump.isTempBasalInProgress = isTempBasalInProgress;
@ -55,8 +53,8 @@ public class MsgStatusTempBasal extends MessageBase {
} }
@NonNull @NonNull
private Date getDateFromTempBasalSecAgo(int tempBasalAgoSecs) { private long getDateFromTempBasalSecAgo(int tempBasalAgoSecs) {
return new Date((long) (Math.ceil(System.currentTimeMillis() / 1000d) - tempBasalAgoSecs) * 1000); return (long) (Math.ceil(System.currentTimeMillis() / 1000d) - tempBasalAgoSecs) * 1000;
} }
public static void updateTempBasalInDB() { public static void updateTempBasalInDB() {
@ -68,11 +66,11 @@ public class MsgStatusTempBasal extends MessageBase {
if (danaRPump.isTempBasalInProgress) { if (danaRPump.isTempBasalInProgress) {
if (tempBasal.percentRate != danaRPump.tempBasalPercent) { if (tempBasal.percentRate != danaRPump.tempBasalPercent) {
// Close current temp basal // Close current temp basal
TemporaryBasal tempStop = new TemporaryBasal().date(danaRPump.tempBasalStart.getTime() - 1000).source(Source.USER); TemporaryBasal tempStop = new TemporaryBasal().date(danaRPump.tempBasalStart - 1000).source(Source.USER);
TreatmentsPlugin.getPlugin().addToHistoryTempBasal(tempStop); TreatmentsPlugin.getPlugin().addToHistoryTempBasal(tempStop);
// Create new // Create new
TemporaryBasal newTempBasal = new TemporaryBasal() TemporaryBasal newTempBasal = new TemporaryBasal()
.date(danaRPump.tempBasalStart.getTime()) .date(danaRPump.tempBasalStart)
.percent(danaRPump.tempBasalPercent) .percent(danaRPump.tempBasalPercent)
.duration(danaRPump.tempBasalTotalSec / 60) .duration(danaRPump.tempBasalTotalSec / 60)
.source(Source.USER); .source(Source.USER);
@ -87,7 +85,7 @@ public class MsgStatusTempBasal extends MessageBase {
if (danaRPump.isTempBasalInProgress) { if (danaRPump.isTempBasalInProgress) {
// Create new // Create new
TemporaryBasal newTempBasal = new TemporaryBasal() TemporaryBasal newTempBasal = new TemporaryBasal()
.date(danaRPump.tempBasalStart.getTime()) .date(danaRPump.tempBasalStart)
.percent(danaRPump.tempBasalPercent) .percent(danaRPump.tempBasalPercent)
.duration(danaRPump.tempBasalTotalSec / 60) .duration(danaRPump.tempBasalTotalSec / 60)
.source(Source.USER); .source(Source.USER);

View file

@ -58,7 +58,8 @@ public abstract class AbstractDanaRExecutionService extends Service {
protected DanaRPump mDanaRPump = DanaRPump.getInstance(); protected DanaRPump mDanaRPump = DanaRPump.getInstance();
protected Treatment mBolusingTreatment = null; protected Treatment mBolusingTreatment = null;
protected Boolean mConnectionInProgress = false; protected boolean mConnectionInProgress = false;
protected boolean mHandshakeInProgress = false;
protected AbstractSerialIOThread mSerialIOThread; protected AbstractSerialIOThread mSerialIOThread;
@ -131,6 +132,15 @@ public abstract class AbstractDanaRExecutionService extends Service {
return mConnectionInProgress; return mConnectionInProgress;
} }
public boolean isHandshakeInProgress() {
return isConnected() && mHandshakeInProgress;
}
public void finishHandshaking() {
mHandshakeInProgress = false;
MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.CONNECTED, 0));
}
public void disconnect(String from) { public void disconnect(String from) {
if (mSerialIOThread != null) if (mSerialIOThread != null)
mSerialIOThread.disconnect(from); mSerialIOThread.disconnect(from);

View file

@ -24,6 +24,7 @@ import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload;
import info.nightscout.androidaps.plugins.Overview.Dialogs.BolusProgressDialog; import info.nightscout.androidaps.plugins.Overview.Dialogs.BolusProgressDialog;
import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification; import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.Overview.events.EventOverviewBolusProgress; import info.nightscout.androidaps.plugins.Overview.events.EventOverviewBolusProgress;
@ -63,7 +64,7 @@ import info.nightscout.androidaps.plugins.PumpDanaR.events.EventDanaRNewStatus;
import info.nightscout.androidaps.plugins.Treatments.Treatment; import info.nightscout.androidaps.plugins.Treatments.Treatment;
import info.nightscout.androidaps.queue.Callback; import info.nightscout.androidaps.queue.Callback;
import info.nightscout.androidaps.queue.commands.Command; import info.nightscout.androidaps.queue.commands.Command;
import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload; import info.nightscout.utils.DateUtil;
import info.nightscout.utils.SP; import info.nightscout.utils.SP;
public class DanaRExecutionService extends AbstractDanaRExecutionService { public class DanaRExecutionService extends AbstractDanaRExecutionService {
@ -109,35 +110,34 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService {
if (mConnectionInProgress) if (mConnectionInProgress)
return; return;
new Thread(new Runnable() { new Thread(() -> {
@Override mHandshakeInProgress = false;
public void run() { mConnectionInProgress = true;
mConnectionInProgress = true; getBTSocketForSelectedPump();
getBTSocketForSelectedPump(); if (mRfcommSocket == null || mBTDevice == null) {
if (mRfcommSocket == null || mBTDevice == null) {
mConnectionInProgress = false;
return; // Device not found
}
try {
mRfcommSocket.connect();
} catch (IOException e) {
//log.error("Unhandled exception", e);
if (e.getMessage().contains("socket closed")) {
log.error("Unhandled exception", e);
}
}
if (isConnected()) {
if (mSerialIOThread != null) {
mSerialIOThread.disconnect("Recreate SerialIOThread");
}
mSerialIOThread = new SerialIOThread(mRfcommSocket);
MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.CONNECTED, 0));
}
mConnectionInProgress = false; mConnectionInProgress = false;
return; // Device not found
} }
try {
mRfcommSocket.connect();
} catch (IOException e) {
//log.error("Unhandled exception", e);
if (e.getMessage().contains("socket closed")) {
log.error("Unhandled exception", e);
}
}
if (isConnected()) {
if (mSerialIOThread != null) {
mSerialIOThread.disconnect("Recreate SerialIOThread");
}
mSerialIOThread = new SerialIOThread(mRfcommSocket);
mHandshakeInProgress = true;
MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.HANDSHAKING, 0));
}
mConnectionInProgress = false;
}).start(); }).start();
} }
@ -193,13 +193,13 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService {
mSerialIOThread.sendMessage(new MsgSettingUserOptions()); mSerialIOThread.sendMessage(new MsgSettingUserOptions());
MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumptime))); MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumptime)));
mSerialIOThread.sendMessage(new MsgSettingPumpTime()); mSerialIOThread.sendMessage(new MsgSettingPumpTime());
long timeDiff = (mDanaRPump.pumpTime.getTime() - System.currentTimeMillis()) / 1000L; long timeDiff = (mDanaRPump.pumpTime - System.currentTimeMillis()) / 1000L;
if (L.isEnabled(L.PUMP)) if (L.isEnabled(L.PUMP))
log.debug("Pump time difference: " + timeDiff + " seconds"); log.debug("Pump time difference: " + timeDiff + " seconds");
if (Math.abs(timeDiff) > 10) { if (Math.abs(timeDiff) > 10) {
mSerialIOThread.sendMessage(new MsgSetTime(new Date())); mSerialIOThread.sendMessage(new MsgSetTime(new Date()));
mSerialIOThread.sendMessage(new MsgSettingPumpTime()); mSerialIOThread.sendMessage(new MsgSettingPumpTime());
timeDiff = (mDanaRPump.pumpTime.getTime() - System.currentTimeMillis()) / 1000L; timeDiff = (mDanaRPump.pumpTime - System.currentTimeMillis()) / 1000L;
if (L.isEnabled(L.PUMP)) if (L.isEnabled(L.PUMP))
log.debug("Pump time difference: " + timeDiff + " seconds"); log.debug("Pump time difference: " + timeDiff + " seconds");
} }
@ -344,13 +344,13 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService {
ConfigBuilderPlugin.getCommandQueue().independentConnect("bolusingInterrupted", new Callback() { ConfigBuilderPlugin.getCommandQueue().independentConnect("bolusingInterrupted", new Callback() {
@Override @Override
public void run() { public void run() {
if (mDanaRPump.lastBolusTime.getTime() > System.currentTimeMillis() - 60 * 1000L) { // last bolus max 1 min old if (mDanaRPump.lastBolusTime > System.currentTimeMillis() - 60 * 1000L) { // last bolus max 1 min old
t.insulin = mDanaRPump.lastBolusAmount; t.insulin = mDanaRPump.lastBolusAmount;
if (L.isEnabled(L.PUMP)) if (L.isEnabled(L.PUMP))
log.debug("Used bolus amount from history: " + mDanaRPump.lastBolusAmount); log.debug("Used bolus amount from history: " + mDanaRPump.lastBolusAmount);
} else { } else {
if (L.isEnabled(L.PUMP)) if (L.isEnabled(L.PUMP))
log.debug("Bolus amount in history too old: " + mDanaRPump.lastBolusTime.toLocaleString()); log.debug("Bolus amount in history too old: " + DateUtil.dateAndTimeFullString(mDanaRPump.lastBolusTime));
} }
synchronized (o) { synchronized (o) {
o.notify(); o.notify();

View file

@ -179,6 +179,16 @@ public class DanaRKoreanPlugin extends AbstractDanaRPlugin {
return pump.lastConnection > 0 && pump.maxBasal > 0 && !pump.isConfigUD && !pump.isEasyModeEnabled && pump.isExtendedBolusEnabled; return pump.lastConnection > 0 && pump.maxBasal > 0 && !pump.isConfigUD && !pump.isEasyModeEnabled && pump.isExtendedBolusEnabled;
} }
@Override
public boolean isHandshakeInProgress() {
return sExecutionService != null && sExecutionService.isHandshakeInProgress();
}
@Override
public void finishHandshaking() {
sExecutionService.finishHandshaking();
}
@Override @Override
public PumpEnactResult deliverTreatment(DetailedBolusInfo detailedBolusInfo) { public PumpEnactResult deliverTreatment(DetailedBolusInfo detailedBolusInfo) {
detailedBolusInfo.insulin = MainApp.getConstraintChecker().applyBolusConstraints(new Constraint<>(detailedBolusInfo.insulin)).value(); detailedBolusInfo.insulin = MainApp.getConstraintChecker().applyBolusConstraints(new Constraint<>(detailedBolusInfo.insulin)).value();

View file

@ -3,8 +3,6 @@ package info.nightscout.androidaps.plugins.PumpDanaRKorean.comm;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.Date;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.events.EventRefreshGui; import info.nightscout.androidaps.events.EventRefreshGui;
@ -17,6 +15,7 @@ import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPlugin;
import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump; import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump;
import info.nightscout.androidaps.plugins.PumpDanaR.comm.MessageBase; import info.nightscout.androidaps.plugins.PumpDanaR.comm.MessageBase;
import info.nightscout.androidaps.plugins.PumpDanaRKorean.DanaRKoreanPlugin; import info.nightscout.androidaps.plugins.PumpDanaRKorean.DanaRKoreanPlugin;
import info.nightscout.utils.DateUtil;
public class MsgInitConnStatusTime_k extends MessageBase { public class MsgInitConnStatusTime_k extends MessageBase {
private static Logger log = LoggerFactory.getLogger(L.PUMPCOMM); private static Logger log = LoggerFactory.getLogger(L.PUMPCOMM);
@ -54,14 +53,14 @@ public class MsgInitConnStatusTime_k extends MessageBase {
return; return;
} }
Date time = dateTimeSecFromBuff(bytes, 0); long time = dateTimeSecFromBuff(bytes, 0);
int versionCode1 = intFromBuff(bytes, 6, 1); int versionCode1 = intFromBuff(bytes, 6, 1);
int versionCode2 = intFromBuff(bytes, 7, 1); int versionCode2 = intFromBuff(bytes, 7, 1);
int versionCode3 = intFromBuff(bytes, 8, 1); int versionCode3 = intFromBuff(bytes, 8, 1);
int versionCode4 = intFromBuff(bytes, 9, 1); int versionCode4 = intFromBuff(bytes, 9, 1);
if (L.isEnabled(L.PUMPCOMM)) { if (L.isEnabled(L.PUMPCOMM)) {
log.debug("Pump time: " + time); log.debug("Pump time: " + DateUtil.dateAndTimeFullString(time));
log.debug("Version code1: " + versionCode1); log.debug("Version code1: " + versionCode1);
log.debug("Version code2: " + versionCode2); log.debug("Version code2: " + versionCode2);
log.debug("Version code3: " + versionCode3); log.debug("Version code3: " + versionCode3);

View file

@ -115,6 +115,7 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService {
return; return;
new Thread(() -> { new Thread(() -> {
mHandshakeInProgress = false;
mConnectionInProgress = true; mConnectionInProgress = true;
getBTSocketForSelectedPump(); getBTSocketForSelectedPump();
if (mRfcommSocket == null || mBTDevice == null) { if (mRfcommSocket == null || mBTDevice == null) {
@ -136,7 +137,8 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService {
mSerialIOThread.disconnect("Recreate SerialIOThread"); mSerialIOThread.disconnect("Recreate SerialIOThread");
} }
mSerialIOThread = new SerialIOThread(mRfcommSocket); mSerialIOThread = new SerialIOThread(mRfcommSocket);
MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.CONNECTED, 0)); mHandshakeInProgress = true;
MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.HANDSHAKING, 0));
} }
mConnectionInProgress = false; mConnectionInProgress = false;
@ -191,13 +193,13 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService {
mSerialIOThread.sendMessage(new MsgSettingProfileRatios()); mSerialIOThread.sendMessage(new MsgSettingProfileRatios());
MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumptime))); MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumptime)));
mSerialIOThread.sendMessage(new MsgSettingPumpTime()); mSerialIOThread.sendMessage(new MsgSettingPumpTime());
long timeDiff = (mDanaRPump.pumpTime.getTime() - System.currentTimeMillis()) / 1000L; long timeDiff = (mDanaRPump.pumpTime - System.currentTimeMillis()) / 1000L;
if (L.isEnabled(L.PUMP)) if (L.isEnabled(L.PUMP))
log.debug("Pump time difference: " + timeDiff + " seconds"); log.debug("Pump time difference: " + timeDiff + " seconds");
if (Math.abs(timeDiff) > 10) { if (Math.abs(timeDiff) > 10) {
mSerialIOThread.sendMessage(new MsgSetTime(new Date())); mSerialIOThread.sendMessage(new MsgSetTime(new Date()));
mSerialIOThread.sendMessage(new MsgSettingPumpTime()); mSerialIOThread.sendMessage(new MsgSettingPumpTime());
timeDiff = (mDanaRPump.pumpTime.getTime() - System.currentTimeMillis()) / 1000L; timeDiff = (mDanaRPump.pumpTime - System.currentTimeMillis()) / 1000L;
if (L.isEnabled(L.PUMP)) if (L.isEnabled(L.PUMP))
log.debug("Pump time difference: " + timeDiff + " seconds"); log.debug("Pump time difference: " + timeDiff + " seconds");
} }
@ -282,7 +284,6 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService {
if (amount > 0) { if (amount > 0) {
MsgBolusProgress progress = new MsgBolusProgress(amount, t); // initialize static variables MsgBolusProgress progress = new MsgBolusProgress(amount, t); // initialize static variables
long bolusStart = System.currentTimeMillis();
if (!stop.stopped) { if (!stop.stopped) {
mSerialIOThread.sendMessage(start); mSerialIOThread.sendMessage(start);

View file

@ -16,8 +16,6 @@ import org.json.JSONObject;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.Date;
import info.nightscout.androidaps.BuildConfig; import info.nightscout.androidaps.BuildConfig;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
@ -223,6 +221,15 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte
return danaRSService != null && danaRSService.isConnecting(); return danaRSService != null && danaRSService.isConnecting();
} }
@Override
public boolean isHandshakeInProgress() {
return false;
}
@Override
public void finishHandshaking() {
}
@Override @Override
public void disconnect(String from) { public void disconnect(String from) {
if (L.isEnabled(L.PUMP)) if (L.isEnabled(L.PUMP))
@ -380,8 +387,8 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte
} }
@Override @Override
public Date lastDataTime() { public long lastDataTime() {
return new Date(DanaRPump.getInstance().lastConnection); return DanaRPump.getInstance().lastConnection;
} }
@Override @Override
@ -725,8 +732,8 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte
status.put("timestamp", DateUtil.toISOString(pump.lastConnection)); status.put("timestamp", DateUtil.toISOString(pump.lastConnection));
extended.put("Version", BuildConfig.VERSION_NAME + "-" + BuildConfig.BUILDVERSION); extended.put("Version", BuildConfig.VERSION_NAME + "-" + BuildConfig.BUILDVERSION);
extended.put("PumpIOB", pump.iob); extended.put("PumpIOB", pump.iob);
if (pump.lastBolusTime.getTime() != 0) { if (pump.lastBolusTime != 0) {
extended.put("LastBolus", pump.lastBolusTime.toLocaleString()); extended.put("LastBolus", DateUtil.dateAndTimeFullString(pump.lastBolusTime));
extended.put("LastBolusAmount", pump.lastBolusAmount); extended.put("LastBolusAmount", pump.lastBolusAmount);
} }
TemporaryBasal tb = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(now); TemporaryBasal tb = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(now);
@ -777,7 +784,7 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte
int agoMin = (int) (agoMsec / 60d / 1000d); int agoMin = (int) (agoMsec / 60d / 1000d);
ret += "LastConn: " + agoMin + " minago\n"; ret += "LastConn: " + agoMin + " minago\n";
} }
if (pump.lastBolusTime.getTime() != 0) { if (pump.lastBolusTime != 0) {
ret += "LastBolus: " + DecimalFormatter.to2Decimal(pump.lastBolusAmount) + "U @" + android.text.format.DateFormat.format("HH:mm", pump.lastBolusTime) + "\n"; ret += "LastBolus: " + DecimalFormatter.to2Decimal(pump.lastBolusAmount) + "U @" + android.text.format.DateFormat.format("HH:mm", pump.lastBolusTime) + "\n";
} }
TemporaryBasal activeTemp = TreatmentsPlugin.getPlugin().getRealTempBasalFromHistory(System.currentTimeMillis()); TemporaryBasal activeTemp = TreatmentsPlugin.getPlugin().getRealTempBasalFromHistory(System.currentTimeMillis());

View file

@ -100,8 +100,8 @@ public class DanaRS_Packet {
return ret; return ret;
} }
public static Date dateTimeSecFromBuff(byte[] buff, int offset) { public static synchronized long dateTimeSecFromBuff(byte[] buff, int offset) {
Date date = return
new Date( new Date(
100 + intFromBuff(buff, offset, 1), 100 + intFromBuff(buff, offset, 1),
intFromBuff(buff, offset + 1, 1) - 1, intFromBuff(buff, offset + 1, 1) - 1,
@ -109,8 +109,7 @@ public class DanaRS_Packet {
intFromBuff(buff, offset + 3, 1), intFromBuff(buff, offset + 3, 1),
intFromBuff(buff, offset + 4, 1), intFromBuff(buff, offset + 4, 1),
intFromBuff(buff, offset + 5, 1) intFromBuff(buff, offset + 5, 1)
); ).getTime();
return date;
} }
protected static int intFromBuff(byte[] b, int srcStart, int srcLength) { protected static int intFromBuff(byte[] b, int srcStart, int srcLength) {
@ -143,14 +142,13 @@ public class DanaRS_Packet {
return new String(strbuff, StandardCharsets.UTF_8); return new String(strbuff, StandardCharsets.UTF_8);
} }
public static Date dateFromBuff(byte[] buff, int offset) { public static long dateFromBuff(byte[] buff, int offset) {
Date date = return
new Date( new Date(
100 + byteArrayToInt(getBytes(buff, offset, 1)), 100 + byteArrayToInt(getBytes(buff, offset, 1)),
byteArrayToInt(getBytes(buff, offset + 1, 1)) - 1, byteArrayToInt(getBytes(buff, offset + 1, 1)) - 1,
byteArrayToInt(getBytes(buff, offset + 2, 1)) byteArrayToInt(getBytes(buff, offset + 2, 1))
); ).getTime();
return date;
} }
@TargetApi(Build.VERSION_CODES.KITKAT) @TargetApi(Build.VERSION_CODES.KITKAT)

View file

@ -83,36 +83,23 @@ public class DanaRS_Packet_APS_History_Events extends DanaRS_Packet {
return; return;
} }
Date datetime = dateTimeSecFromBuff(data, 1); // 6 bytes long datetime = dateTimeSecFromBuff(data, 1); // 6 bytes
int param1 = ((intFromBuff(data, 7, 1) << 8) & 0xFF00) + (intFromBuff(data, 8, 1) & 0xFF); int param1 = ((intFromBuff(data, 7, 1) << 8) & 0xFF00) + (intFromBuff(data, 8, 1) & 0xFF);
int param2 = ((intFromBuff(data, 9, 1) << 8) & 0xFF00) + (intFromBuff(data, 10, 1) & 0xFF); int param2 = ((intFromBuff(data, 9, 1) << 8) & 0xFF00) + (intFromBuff(data, 10, 1) & 0xFF);
TemporaryBasal temporaryBasal = new TemporaryBasal().date(datetime.getTime()).source(Source.PUMP).pumpId(datetime.getTime()); TemporaryBasal temporaryBasal = new TemporaryBasal().date(datetime).source(Source.PUMP).pumpId(datetime);
ExtendedBolus extendedBolus = new ExtendedBolus(); ExtendedBolus extendedBolus = new ExtendedBolus();
extendedBolus.date = datetime.getTime(); extendedBolus.date = datetime;
extendedBolus.source = Source.PUMP; extendedBolus.source = Source.PUMP;
extendedBolus.pumpId = datetime.getTime(); extendedBolus.pumpId = datetime;
DetailedBolusInfo detailedBolusInfo = DetailedBolusInfoStorage.findDetailedBolusInfo(datetime.getTime());
if (detailedBolusInfo == null) {
if (L.isEnabled(L.PUMPCOMM))
log.debug("Detailed bolus info not found for " + datetime.toLocaleString());
detailedBolusInfo = new DetailedBolusInfo();
} else {
if (L.isEnabled(L.PUMPCOMM))
log.debug("Detailed bolus info found: " + detailedBolusInfo);
}
detailedBolusInfo.date = datetime.getTime();
detailedBolusInfo.source = Source.PUMP;
detailedBolusInfo.pumpId = datetime.getTime();
String status; String status;
switch (recordCode) { switch (recordCode) {
case DanaRPump.TEMPSTART: case DanaRPump.TEMPSTART:
if (L.isEnabled(L.PUMPCOMM)) if (L.isEnabled(L.PUMPCOMM))
log.debug("EVENT TEMPSTART (" + recordCode + ") " + datetime.toLocaleString() + " Ratio: " + param1 + "% Duration: " + param2 + "min"); log.debug("EVENT TEMPSTART (" + recordCode + ") " + DateUtil.dateAndTimeFullString(datetime) + " (" + datetime + ")" + " Ratio: " + param1 + "% Duration: " + param2 + "min");
temporaryBasal.percentRate = param1; temporaryBasal.percentRate = param1;
temporaryBasal.durationInMinutes = param2; temporaryBasal.durationInMinutes = param2;
TreatmentsPlugin.getPlugin().addToHistoryTempBasal(temporaryBasal); TreatmentsPlugin.getPlugin().addToHistoryTempBasal(temporaryBasal);
@ -120,13 +107,13 @@ public class DanaRS_Packet_APS_History_Events extends DanaRS_Packet {
break; break;
case DanaRPump.TEMPSTOP: case DanaRPump.TEMPSTOP:
if (L.isEnabled(L.PUMPCOMM)) if (L.isEnabled(L.PUMPCOMM))
log.debug("EVENT TEMPSTOP (" + recordCode + ") " + datetime.toLocaleString()); log.debug("EVENT TEMPSTOP (" + recordCode + ") " + DateUtil.dateAndTimeFullString(datetime));
TreatmentsPlugin.getPlugin().addToHistoryTempBasal(temporaryBasal); TreatmentsPlugin.getPlugin().addToHistoryTempBasal(temporaryBasal);
status = "TEMPSTOP " + DateUtil.timeString(datetime); status = "TEMPSTOP " + DateUtil.timeString(datetime);
break; break;
case DanaRPump.EXTENDEDSTART: case DanaRPump.EXTENDEDSTART:
if (L.isEnabled(L.PUMPCOMM)) if (L.isEnabled(L.PUMPCOMM))
log.debug("EVENT EXTENDEDSTART (" + recordCode + ") " + datetime.toLocaleString() + " Amount: " + (param1 / 100d) + "U Duration: " + param2 + "min"); log.debug("EVENT EXTENDEDSTART (" + recordCode + ") " + DateUtil.dateAndTimeFullString(datetime) + " (" + datetime + ")" + " Amount: " + (param1 / 100d) + "U Duration: " + param2 + "min");
extendedBolus.insulin = param1 / 100d; extendedBolus.insulin = param1 / 100d;
extendedBolus.durationInMinutes = param2; extendedBolus.durationInMinutes = param2;
TreatmentsPlugin.getPlugin().addToHistoryExtendedBolus(extendedBolus); TreatmentsPlugin.getPlugin().addToHistoryExtendedBolus(extendedBolus);
@ -134,29 +121,43 @@ public class DanaRS_Packet_APS_History_Events extends DanaRS_Packet {
break; break;
case DanaRPump.EXTENDEDSTOP: case DanaRPump.EXTENDEDSTOP:
if (L.isEnabled(L.PUMPCOMM)) if (L.isEnabled(L.PUMPCOMM))
log.debug("EVENT EXTENDEDSTOP (" + recordCode + ") " + datetime.toLocaleString() + " Delivered: " + (param1 / 100d) + "U RealDuration: " + param2 + "min"); log.debug("EVENT EXTENDEDSTOP (" + recordCode + ") " + DateUtil.dateAndTimeFullString(datetime) + " (" + datetime + ")" + " Delivered: " + (param1 / 100d) + "U RealDuration: " + param2 + "min");
TreatmentsPlugin.getPlugin().addToHistoryExtendedBolus(extendedBolus); TreatmentsPlugin.getPlugin().addToHistoryExtendedBolus(extendedBolus);
status = "EXTENDEDSTOP " + DateUtil.timeString(datetime); status = "EXTENDEDSTOP " + DateUtil.timeString(datetime);
break; break;
case DanaRPump.BOLUS: case DanaRPump.BOLUS:
DetailedBolusInfo detailedBolusInfo = DetailedBolusInfoStorage.findDetailedBolusInfo(datetime);
if (detailedBolusInfo == null) {
detailedBolusInfo = new DetailedBolusInfo();
}
detailedBolusInfo.date = datetime;
detailedBolusInfo.source = Source.PUMP;
detailedBolusInfo.pumpId = datetime;
detailedBolusInfo.insulin = param1 / 100d; detailedBolusInfo.insulin = param1 / 100d;
boolean newRecord = TreatmentsPlugin.getPlugin().addToHistoryTreatment(detailedBolusInfo, false); boolean newRecord = TreatmentsPlugin.getPlugin().addToHistoryTreatment(detailedBolusInfo, false);
if (L.isEnabled(L.PUMPCOMM)) if (L.isEnabled(L.PUMPCOMM))
log.debug((newRecord ? "**NEW** " : "") + "EVENT BOLUS (" + recordCode + ") " + datetime.toLocaleString() + " Bolus: " + (param1 / 100d) + "U Duration: " + param2 + "min"); log.debug((newRecord ? "**NEW** " : "") + "EVENT BOLUS (" + recordCode + ") " + DateUtil.dateAndTimeFullString(datetime) + " (" + datetime + ")" + " Bolus: " + (param1 / 100d) + "U Duration: " + param2 + "min");
DetailedBolusInfoStorage.remove(detailedBolusInfo.date);
status = "BOLUS " + DateUtil.timeString(datetime); status = "BOLUS " + DateUtil.timeString(datetime);
break; break;
case DanaRPump.DUALBOLUS: case DanaRPump.DUALBOLUS:
detailedBolusInfo = DetailedBolusInfoStorage.findDetailedBolusInfo(datetime);
if (detailedBolusInfo == null) {
detailedBolusInfo = new DetailedBolusInfo();
}
detailedBolusInfo.date = datetime;
detailedBolusInfo.source = Source.PUMP;
detailedBolusInfo.pumpId = datetime;
detailedBolusInfo.insulin = param1 / 100d; detailedBolusInfo.insulin = param1 / 100d;
newRecord = TreatmentsPlugin.getPlugin().addToHistoryTreatment(detailedBolusInfo, false); newRecord = TreatmentsPlugin.getPlugin().addToHistoryTreatment(detailedBolusInfo, false);
if (L.isEnabled(L.PUMPCOMM)) if (L.isEnabled(L.PUMPCOMM))
log.debug((newRecord ? "**NEW** " : "") + "EVENT DUALBOLUS (" + recordCode + ") " + datetime.toLocaleString() + " Bolus: " + (param1 / 100d) + "U Duration: " + param2 + "min"); log.debug((newRecord ? "**NEW** " : "") + "EVENT DUALBOLUS (" + recordCode + ") " + DateUtil.dateAndTimeFullString(datetime) + " (" + datetime + ")" + " Bolus: " + (param1 / 100d) + "U Duration: " + param2 + "min");
DetailedBolusInfoStorage.remove(detailedBolusInfo.date);
status = "DUALBOLUS " + DateUtil.timeString(datetime); status = "DUALBOLUS " + DateUtil.timeString(datetime);
break; break;
case DanaRPump.DUALEXTENDEDSTART: case DanaRPump.DUALEXTENDEDSTART:
if (L.isEnabled(L.PUMPCOMM)) if (L.isEnabled(L.PUMPCOMM))
log.debug("EVENT DUALEXTENDEDSTART (" + recordCode + ") " + datetime.toLocaleString() + " Amount: " + (param1 / 100d) + "U Duration: " + param2 + "min"); log.debug("EVENT DUALEXTENDEDSTART (" + recordCode + ") " + DateUtil.dateAndTimeFullString(datetime) + " (" + datetime + ")" + " Amount: " + (param1 / 100d) + "U Duration: " + param2 + "min");
extendedBolus.insulin = param1 / 100d; extendedBolus.insulin = param1 / 100d;
extendedBolus.durationInMinutes = param2; extendedBolus.durationInMinutes = param2;
TreatmentsPlugin.getPlugin().addToHistoryExtendedBolus(extendedBolus); TreatmentsPlugin.getPlugin().addToHistoryExtendedBolus(extendedBolus);
@ -164,60 +165,60 @@ public class DanaRS_Packet_APS_History_Events extends DanaRS_Packet {
break; break;
case DanaRPump.DUALEXTENDEDSTOP: case DanaRPump.DUALEXTENDEDSTOP:
if (L.isEnabled(L.PUMPCOMM)) if (L.isEnabled(L.PUMPCOMM))
log.debug("EVENT DUALEXTENDEDSTOP (" + recordCode + ") " + datetime.toLocaleString() + " Delivered: " + (param1 / 100d) + "U RealDuration: " + param2 + "min"); log.debug("EVENT DUALEXTENDEDSTOP (" + recordCode + ") " + DateUtil.dateAndTimeFullString(datetime) + " (" + datetime + ")" + " Delivered: " + (param1 / 100d) + "U RealDuration: " + param2 + "min");
TreatmentsPlugin.getPlugin().addToHistoryExtendedBolus(extendedBolus); TreatmentsPlugin.getPlugin().addToHistoryExtendedBolus(extendedBolus);
status = "DUALEXTENDEDSTOP " + DateUtil.timeString(datetime); status = "DUALEXTENDEDSTOP " + DateUtil.timeString(datetime);
break; break;
case DanaRPump.SUSPENDON: case DanaRPump.SUSPENDON:
if (L.isEnabled(L.PUMPCOMM)) if (L.isEnabled(L.PUMPCOMM))
log.debug("EVENT SUSPENDON (" + recordCode + ") " + datetime.toLocaleString()); log.debug("EVENT SUSPENDON (" + recordCode + ") " + DateUtil.dateAndTimeFullString(datetime) + " (" + datetime + ")");
status = "SUSPENDON " + DateUtil.timeString(datetime); status = "SUSPENDON " + DateUtil.timeString(datetime);
break; break;
case DanaRPump.SUSPENDOFF: case DanaRPump.SUSPENDOFF:
if (L.isEnabled(L.PUMPCOMM)) if (L.isEnabled(L.PUMPCOMM))
log.debug("EVENT SUSPENDOFF (" + recordCode + ") " + datetime.toLocaleString()); log.debug("EVENT SUSPENDOFF (" + recordCode + ") " + DateUtil.dateAndTimeFullString(datetime) + " (" + datetime + ")");
status = "SUSPENDOFF " + DateUtil.timeString(datetime); status = "SUSPENDOFF " + DateUtil.timeString(datetime);
break; break;
case DanaRPump.REFILL: case DanaRPump.REFILL:
if (L.isEnabled(L.PUMPCOMM)) if (L.isEnabled(L.PUMPCOMM))
log.debug("EVENT REFILL (" + recordCode + ") " + datetime.toLocaleString() + " Amount: " + param1 / 100d + "U"); log.debug("EVENT REFILL (" + recordCode + ") " + DateUtil.dateAndTimeFullString(datetime) + " (" + datetime + ")" + " Amount: " + param1 / 100d + "U");
status = "REFILL " + DateUtil.timeString(datetime); status = "REFILL " + DateUtil.timeString(datetime);
break; break;
case DanaRPump.PRIME: case DanaRPump.PRIME:
if (L.isEnabled(L.PUMPCOMM)) if (L.isEnabled(L.PUMPCOMM))
log.debug("EVENT PRIME (" + recordCode + ") " + datetime.toLocaleString() + " Amount: " + param1 / 100d + "U"); log.debug("EVENT PRIME (" + recordCode + ") " + DateUtil.dateAndTimeFullString(datetime) + " (" + datetime + ")" + " Amount: " + param1 / 100d + "U");
status = "PRIME " + DateUtil.timeString(datetime); status = "PRIME " + DateUtil.timeString(datetime);
break; break;
case DanaRPump.PROFILECHANGE: case DanaRPump.PROFILECHANGE:
if (L.isEnabled(L.PUMPCOMM)) if (L.isEnabled(L.PUMPCOMM))
log.debug("EVENT PROFILECHANGE (" + recordCode + ") " + datetime.toLocaleString() + " No: " + param1 + " CurrentRate: " + (param2 / 100d) + "U/h"); log.debug("EVENT PROFILECHANGE (" + recordCode + ") " + DateUtil.dateAndTimeFullString(datetime) + " (" + datetime + ")" + " No: " + param1 + " CurrentRate: " + (param2 / 100d) + "U/h");
status = "PROFILECHANGE " + DateUtil.timeString(datetime); status = "PROFILECHANGE " + DateUtil.timeString(datetime);
break; break;
case DanaRPump.CARBS: case DanaRPump.CARBS:
DetailedBolusInfo emptyCarbsInfo = new DetailedBolusInfo(); DetailedBolusInfo emptyCarbsInfo = new DetailedBolusInfo();
emptyCarbsInfo.carbs = param1; emptyCarbsInfo.carbs = param1;
emptyCarbsInfo.date = datetime.getTime(); emptyCarbsInfo.date = datetime;
emptyCarbsInfo.source = Source.PUMP; emptyCarbsInfo.source = Source.PUMP;
emptyCarbsInfo.pumpId = datetime.getTime(); emptyCarbsInfo.pumpId = datetime;
newRecord = TreatmentsPlugin.getPlugin().addToHistoryTreatment(emptyCarbsInfo, false); newRecord = TreatmentsPlugin.getPlugin().addToHistoryTreatment(emptyCarbsInfo, false);
if (L.isEnabled(L.PUMPCOMM)) if (L.isEnabled(L.PUMPCOMM))
log.debug((newRecord ? "**NEW** " : "") + "EVENT CARBS (" + recordCode + ") " + datetime.toLocaleString() + " Carbs: " + param1 + "g"); log.debug((newRecord ? "**NEW** " : "") + "EVENT CARBS (" + recordCode + ") " + DateUtil.dateAndTimeFullString(datetime) + " (" + datetime + ")" + " Carbs: " + param1 + "g");
status = "CARBS " + DateUtil.timeString(datetime); status = "CARBS " + DateUtil.timeString(datetime);
break; break;
case DanaRPump.PRIMECANNULA: case DanaRPump.PRIMECANNULA:
if (L.isEnabled(L.PUMPCOMM)) if (L.isEnabled(L.PUMPCOMM))
log.debug("EVENT PRIMECANNULA(" + recordCode + ") " + datetime.toLocaleString() + " Amount: " + param1 / 100d + "U"); log.debug("EVENT PRIMECANNULA(" + recordCode + ") " + DateUtil.dateAndTimeFullString(datetime) + " (" + datetime + ")" + " Amount: " + param1 / 100d + "U");
status = "PRIMECANNULA " + DateUtil.timeString(datetime); status = "PRIMECANNULA " + DateUtil.timeString(datetime);
break; break;
default: default:
if (L.isEnabled(L.PUMPCOMM)) if (L.isEnabled(L.PUMPCOMM))
log.debug("Event: " + recordCode + " " + datetime.toLocaleString() + " Param1: " + param1 + " Param2: " + param2); log.debug("Event: " + recordCode + " " + DateUtil.dateAndTimeFullString(datetime) + " (" + datetime + ")" + " Param1: " + param1 + " Param2: " + param2);
status = "UNKNOWN " + DateUtil.timeString(datetime); status = "UNKNOWN " + DateUtil.timeString(datetime);
break; break;
} }
if (datetime.getTime() > lastEventTimeLoaded) if (datetime > lastEventTimeLoaded)
lastEventTimeLoaded = datetime.getTime(); lastEventTimeLoaded = datetime;
MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.processinghistory) + ": " + status)); MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.processinghistory) + ": " + status));
} }

View file

@ -7,10 +7,9 @@ import com.cozmo.danar.util.BleCommandUtil;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.Date;
import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump; import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump;
import info.nightscout.utils.DateUtil;
public class DanaRS_Packet_Basal_Get_Temporary_Basal_State extends DanaRS_Packet { public class DanaRS_Packet_Basal_Get_Temporary_Basal_State extends DanaRS_Packet {
private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); private Logger log = LoggerFactory.getLogger(L.PUMPCOMM);
@ -55,7 +54,7 @@ public class DanaRS_Packet_Basal_Get_Temporary_Basal_State extends DanaRS_Packet
dataSize = 2; dataSize = 2;
int runningMin = byteArrayToInt(getBytes(data, dataIndex, dataSize)); int runningMin = byteArrayToInt(getBytes(data, dataIndex, dataSize));
int tempBasalRemainingMin = (pump.tempBasalTotalSec - runningMin * 60) / 60; int tempBasalRemainingMin = (pump.tempBasalTotalSec - runningMin * 60) / 60;
Date tempBasalStart = pump.isTempBasalInProgress ? getDateFromTempBasalSecAgo(runningMin * 60) : new Date(0); long tempBasalStart = pump.isTempBasalInProgress ? getDateFromTempBasalSecAgo(runningMin * 60) : 0;
if (L.isEnabled(L.PUMPCOMM)) { if (L.isEnabled(L.PUMPCOMM)) {
log.debug("Error code: " + error); log.debug("Error code: " + error);
@ -64,7 +63,7 @@ public class DanaRS_Packet_Basal_Get_Temporary_Basal_State extends DanaRS_Packet
log.debug("Current temp basal percent: " + pump.tempBasalPercent); log.debug("Current temp basal percent: " + pump.tempBasalPercent);
log.debug("Current temp basal remaining min: " + tempBasalRemainingMin); log.debug("Current temp basal remaining min: " + tempBasalRemainingMin);
log.debug("Current temp basal total sec: " + pump.tempBasalTotalSec); log.debug("Current temp basal total sec: " + pump.tempBasalTotalSec);
log.debug("Current temp basal start: " + tempBasalStart); log.debug("Current temp basal start: " + DateUtil.dateAndTimeFullString(tempBasalStart));
} }
} }
@ -74,8 +73,8 @@ public class DanaRS_Packet_Basal_Get_Temporary_Basal_State extends DanaRS_Packet
} }
@NonNull @NonNull
private Date getDateFromTempBasalSecAgo(int tempBasalAgoSecs) { private long getDateFromTempBasalSecAgo(int tempBasalAgoSecs) {
return new Date((long) (Math.ceil(System.currentTimeMillis() / 1000d) - tempBasalAgoSecs) * 1000); return (long) (Math.ceil(System.currentTimeMillis() / 1000d) - tempBasalAgoSecs) * 1000;
} }
} }

View file

@ -9,6 +9,7 @@ import java.util.Date;
import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump; import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump;
import info.nightscout.utils.DateUtil;
public class DanaRS_Packet_Bolus_Get_Step_Bolus_Information extends DanaRS_Packet { public class DanaRS_Packet_Bolus_Get_Step_Bolus_Information extends DanaRS_Packet {
private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); private Logger log = LoggerFactory.getLogger(L.PUMPCOMM);
@ -36,14 +37,16 @@ public class DanaRS_Packet_Bolus_Get_Step_Bolus_Information extends DanaRS_Packe
dataSize = 2; dataSize = 2;
pump.initialBolusAmount = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100d; pump.initialBolusAmount = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100d;
pump.lastBolusTime = new Date(); // it doesn't provide day only hour+min, workaround: expecting today Date lbt = new Date(); // it doesn't provide day only hour+min, workaround: expecting today
dataIndex += dataSize; dataIndex += dataSize;
dataSize = 1; dataSize = 1;
pump.lastBolusTime.setHours(byteArrayToInt(getBytes(data, dataIndex, dataSize))); lbt.setHours(byteArrayToInt(getBytes(data, dataIndex, dataSize)));
dataIndex += dataSize; dataIndex += dataSize;
dataSize = 1; dataSize = 1;
pump.lastBolusTime.setMinutes(byteArrayToInt(getBytes(data, dataIndex, dataSize))); lbt.setMinutes(byteArrayToInt(getBytes(data, dataIndex, dataSize)));
pump.lastBolusTime = lbt.getTime();
dataIndex += dataSize; dataIndex += dataSize;
dataSize = 2; dataSize = 2;
@ -56,13 +59,13 @@ public class DanaRS_Packet_Bolus_Get_Step_Bolus_Information extends DanaRS_Packe
dataIndex += dataSize; dataIndex += dataSize;
dataSize = 1; dataSize = 1;
pump.bolusStep = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100d; pump.bolusStep = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100d;
if ( error != 0) if (error != 0)
failed = true; failed = true;
if (L.isEnabled(L.PUMPCOMM)) { if (L.isEnabled(L.PUMPCOMM)) {
log.debug("Result: " + error); log.debug("Result: " + error);
log.debug("BolusType: " + bolusType); log.debug("BolusType: " + bolusType);
log.debug("Initial bolus amount: " + pump.initialBolusAmount + " U"); log.debug("Initial bolus amount: " + pump.initialBolusAmount + " U");
log.debug("Last bolus time: " + pump.lastBolusTime.toLocaleString()); log.debug("Last bolus time: " + DateUtil.dateAndTimeFullString(pump.lastBolusTime));
log.debug("Last bolus amount: " + pump.lastBolusAmount); log.debug("Last bolus amount: " + pump.lastBolusAmount);
log.debug("Max bolus: " + pump.maxBolus + " U"); log.debug("Max bolus: " + pump.maxBolus + " U");
log.debug("Bolus step: " + pump.bolusStep + " U"); log.debug("Bolus step: " + pump.bolusStep + " U");

View file

@ -7,6 +7,7 @@ import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump; import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump;
import info.nightscout.utils.DateUtil;
public class DanaRS_Packet_General_Get_Shipping_Information extends DanaRS_Packet { public class DanaRS_Packet_General_Get_Shipping_Information extends DanaRS_Packet {
private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); private Logger log = LoggerFactory.getLogger(L.PUMPCOMM);
@ -20,7 +21,7 @@ public class DanaRS_Packet_General_Get_Shipping_Information extends DanaRS_Packe
@Override @Override
public void handleMessage(byte[] data) { public void handleMessage(byte[] data) {
if (data.length < 18){ if (data.length < 18) {
failed = true; failed = true;
return; return;
} }
@ -40,7 +41,7 @@ public class DanaRS_Packet_General_Get_Shipping_Information extends DanaRS_Packe
if (L.isEnabled(L.PUMPCOMM)) { if (L.isEnabled(L.PUMPCOMM)) {
log.debug("Serial number: " + pump.serialNumber); log.debug("Serial number: " + pump.serialNumber);
log.debug("Shipping date: " + pump.shippingDate); log.debug("Shipping date: " + DateUtil.dateAndTimeString(pump.shippingDate));
log.debug("Shipping country: " + pump.shippingCountry); log.debug("Shipping country: " + pump.shippingCountry);
} }
} }

View file

@ -33,11 +33,11 @@ public abstract class DanaRS_Packet_History_ extends DanaRS_Packet {
totalCount = 0; totalCount = 0;
} }
public DanaRS_Packet_History_(Date from) { public DanaRS_Packet_History_(long from) {
this(); this();
GregorianCalendar cal = new GregorianCalendar(); GregorianCalendar cal = new GregorianCalendar();
if (from.getTime() != 0) if (from != 0)
cal.setTime(from); cal.setTimeInMillis(from);
else else
cal.set(2000, 0, 1, 0, 0, 0); cal.set(2000, 0, 1, 0, 0, 0);
year = cal.get(Calendar.YEAR) - 1900 - 100; year = cal.get(Calendar.YEAR) - 1900 - 100;

View file

@ -17,7 +17,7 @@ public class DanaRS_Packet_History_Alarm extends DanaRS_Packet_History_ {
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__ALARM; opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__ALARM;
} }
public DanaRS_Packet_History_Alarm(Date from) { public DanaRS_Packet_History_Alarm(long from) {
super(from); super(from);
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__ALARM; opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__ALARM;
if (L.isEnabled(L.PUMPCOMM)) if (L.isEnabled(L.PUMPCOMM))

View file

@ -5,8 +5,6 @@ import com.cozmo.danar.util.BleCommandUtil;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.Date;
import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.L;
public class DanaRS_Packet_History_All_History extends DanaRS_Packet_History_ { public class DanaRS_Packet_History_All_History extends DanaRS_Packet_History_ {
@ -17,7 +15,7 @@ public class DanaRS_Packet_History_All_History extends DanaRS_Packet_History_ {
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__ALL_HISTORY; opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__ALL_HISTORY;
} }
public DanaRS_Packet_History_All_History(Date from) { public DanaRS_Packet_History_All_History(long from) {
super(from); super(from);
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__ALL_HISTORY; opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__ALL_HISTORY;
if (L.isEnabled(L.PUMPCOMM)) if (L.isEnabled(L.PUMPCOMM))

View file

@ -5,8 +5,6 @@ import com.cozmo.danar.util.BleCommandUtil;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.Date;
import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.L;
public class DanaRS_Packet_History_Basal extends DanaRS_Packet_History_ { public class DanaRS_Packet_History_Basal extends DanaRS_Packet_History_ {
@ -17,7 +15,7 @@ public class DanaRS_Packet_History_Basal extends DanaRS_Packet_History_ {
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__BASAL; opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__BASAL;
} }
public DanaRS_Packet_History_Basal(Date from) { public DanaRS_Packet_History_Basal(long from) {
super(from); super(from);
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__BASAL; opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__BASAL;
if (L.isEnabled(L.PUMPCOMM)) if (L.isEnabled(L.PUMPCOMM))

View file

@ -5,8 +5,6 @@ import com.cozmo.danar.util.BleCommandUtil;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.Date;
import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.L;
public class DanaRS_Packet_History_Blood_Glucose extends DanaRS_Packet_History_ { public class DanaRS_Packet_History_Blood_Glucose extends DanaRS_Packet_History_ {
@ -17,7 +15,7 @@ public class DanaRS_Packet_History_Blood_Glucose extends DanaRS_Packet_History_
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__BLOOD_GLUCOSE; opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__BLOOD_GLUCOSE;
} }
public DanaRS_Packet_History_Blood_Glucose(Date from) { public DanaRS_Packet_History_Blood_Glucose(long from) {
super(from); super(from);
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__BLOOD_GLUCOSE; opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__BLOOD_GLUCOSE;
if (L.isEnabled(L.PUMPCOMM)) if (L.isEnabled(L.PUMPCOMM))

View file

@ -5,8 +5,6 @@ import com.cozmo.danar.util.BleCommandUtil;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.Date;
import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.L;
public class DanaRS_Packet_History_Bolus extends DanaRS_Packet_History_ { public class DanaRS_Packet_History_Bolus extends DanaRS_Packet_History_ {
@ -17,7 +15,7 @@ public class DanaRS_Packet_History_Bolus extends DanaRS_Packet_History_ {
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__BOLUS; opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__BOLUS;
} }
public DanaRS_Packet_History_Bolus(Date from) { public DanaRS_Packet_History_Bolus(long from) {
super(from); super(from);
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__BOLUS; opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__BOLUS;
if (L.isEnabled(L.PUMPCOMM)) if (L.isEnabled(L.PUMPCOMM))

View file

@ -5,8 +5,6 @@ import com.cozmo.danar.util.BleCommandUtil;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.Date;
import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.L;
public class DanaRS_Packet_History_Carbohydrate extends DanaRS_Packet_History_ { public class DanaRS_Packet_History_Carbohydrate extends DanaRS_Packet_History_ {
@ -17,7 +15,7 @@ public class DanaRS_Packet_History_Carbohydrate extends DanaRS_Packet_History_ {
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__CARBOHYDRATE; opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__CARBOHYDRATE;
} }
public DanaRS_Packet_History_Carbohydrate(Date from) { public DanaRS_Packet_History_Carbohydrate(long from) {
super(from); super(from);
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__CARBOHYDRATE; opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__CARBOHYDRATE;
if (L.isEnabled(L.PUMPCOMM)) if (L.isEnabled(L.PUMPCOMM))

View file

@ -5,8 +5,6 @@ import com.cozmo.danar.util.BleCommandUtil;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.Date;
import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.L;
public class DanaRS_Packet_History_Daily extends DanaRS_Packet_History_ { public class DanaRS_Packet_History_Daily extends DanaRS_Packet_History_ {
@ -17,7 +15,7 @@ public class DanaRS_Packet_History_Daily extends DanaRS_Packet_History_ {
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__DAILY; opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__DAILY;
} }
public DanaRS_Packet_History_Daily(Date from) { public DanaRS_Packet_History_Daily(long from) {
super(from); super(from);
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__DAILY; opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__DAILY;
if (L.isEnabled(L.PUMPCOMM)) if (L.isEnabled(L.PUMPCOMM))

View file

@ -5,8 +5,6 @@ import com.cozmo.danar.util.BleCommandUtil;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.Date;
import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.L;
public class DanaRS_Packet_History_Prime extends DanaRS_Packet_History_ { public class DanaRS_Packet_History_Prime extends DanaRS_Packet_History_ {
@ -17,7 +15,7 @@ public class DanaRS_Packet_History_Prime extends DanaRS_Packet_History_ {
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__PRIME; opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__PRIME;
} }
public DanaRS_Packet_History_Prime(Date from) { public DanaRS_Packet_History_Prime(long from) {
super(from); super(from);
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__PRIME; opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__PRIME;
if (L.isEnabled(L.PUMPCOMM)) if (L.isEnabled(L.PUMPCOMM))

View file

@ -5,8 +5,6 @@ import com.cozmo.danar.util.BleCommandUtil;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.Date;
import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.L;
public class DanaRS_Packet_History_Refill extends DanaRS_Packet_History_ { public class DanaRS_Packet_History_Refill extends DanaRS_Packet_History_ {
@ -17,7 +15,7 @@ public class DanaRS_Packet_History_Refill extends DanaRS_Packet_History_ {
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__REFILL; opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__REFILL;
} }
public DanaRS_Packet_History_Refill(Date from) { public DanaRS_Packet_History_Refill(long from) {
super(from); super(from);
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__REFILL; opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__REFILL;
if (L.isEnabled(L.PUMPCOMM)) if (L.isEnabled(L.PUMPCOMM))

View file

@ -5,8 +5,6 @@ import com.cozmo.danar.util.BleCommandUtil;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.Date;
import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.L;
public class DanaRS_Packet_History_Suspend extends DanaRS_Packet_History_ { public class DanaRS_Packet_History_Suspend extends DanaRS_Packet_History_ {
@ -17,7 +15,7 @@ public class DanaRS_Packet_History_Suspend extends DanaRS_Packet_History_ {
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__SUSPEND; opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__SUSPEND;
} }
public DanaRS_Packet_History_Suspend(Date from) { public DanaRS_Packet_History_Suspend(long from) {
super(from); super(from);
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__SUSPEND; opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__SUSPEND;
if (L.isEnabled(L.PUMPCOMM)) if (L.isEnabled(L.PUMPCOMM))

View file

@ -5,8 +5,6 @@ import com.cozmo.danar.util.BleCommandUtil;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.Date;
import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.L;
public class DanaRS_Packet_History_Temporary extends DanaRS_Packet_History_ { public class DanaRS_Packet_History_Temporary extends DanaRS_Packet_History_ {
@ -17,7 +15,7 @@ public class DanaRS_Packet_History_Temporary extends DanaRS_Packet_History_ {
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__TEMPORARY; opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__TEMPORARY;
} }
public DanaRS_Packet_History_Temporary(Date from) { public DanaRS_Packet_History_Temporary(long from) {
super(from); super(from);
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__TEMPORARY; opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__TEMPORARY;
if (L.isEnabled(L.PUMPCOMM)) if (L.isEnabled(L.PUMPCOMM))

View file

@ -48,7 +48,7 @@ public class DanaRS_Packet_Option_Get_Pump_Time extends DanaRS_Packet {
int sec = byteArrayToInt(getBytes(data, dataIndex, dataSize)); int sec = byteArrayToInt(getBytes(data, dataIndex, dataSize));
Date time = new Date(100 + year, month - 1, day, hour, min, sec); Date time = new Date(100 + year, month - 1, day, hour, min, sec);
DanaRPump.getInstance().pumpTime = time; DanaRPump.getInstance().pumpTime = time.getTime();
if ( year == month && month == day && day == hour && hour == min && min == sec && sec == 1) if ( year == month && month == day && day == hour && hour == min && min == sec && sec == 1)
failed = true; failed = true;

View file

@ -156,7 +156,7 @@ public class DanaRSService extends Service {
MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumptime))); MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumptime)));
bleComm.sendMessage(new DanaRS_Packet_Option_Get_Pump_Time()); bleComm.sendMessage(new DanaRS_Packet_Option_Get_Pump_Time());
long timeDiff = (danaRPump.pumpTime.getTime() - System.currentTimeMillis()) / 1000L; long timeDiff = (danaRPump.pumpTime - System.currentTimeMillis()) / 1000L;
if (L.isEnabled(L.PUMPCOMM)) if (L.isEnabled(L.PUMPCOMM))
log.debug("Pump time difference: " + timeDiff + " seconds"); log.debug("Pump time difference: " + timeDiff + " seconds");
if (Math.abs(timeDiff) > 3) { if (Math.abs(timeDiff) > 3) {
@ -181,7 +181,7 @@ public class DanaRSService extends Service {
// add 10sec to be sure we are over minute (will be cutted off anyway) // add 10sec to be sure we are over minute (will be cutted off anyway)
bleComm.sendMessage(new DanaRS_Packet_Option_Set_Pump_Time(new Date(DateUtil.now() + T.secs(10).msecs()))); bleComm.sendMessage(new DanaRS_Packet_Option_Set_Pump_Time(new Date(DateUtil.now() + T.secs(10).msecs())));
bleComm.sendMessage(new DanaRS_Packet_Option_Get_Pump_Time()); bleComm.sendMessage(new DanaRS_Packet_Option_Get_Pump_Time());
timeDiff = (danaRPump.pumpTime.getTime() - System.currentTimeMillis()) / 1000L; timeDiff = (danaRPump.pumpTime - System.currentTimeMillis()) / 1000L;
if (L.isEnabled(L.PUMPCOMM)) if (L.isEnabled(L.PUMPCOMM))
log.debug("Pump time difference: " + timeDiff + " seconds"); log.debug("Pump time difference: " + timeDiff + " seconds");
} }
@ -241,7 +241,7 @@ public class DanaRSService extends Service {
} else { } else {
msg = new DanaRS_Packet_APS_History_Events(lastHistoryFetched); msg = new DanaRS_Packet_APS_History_Events(lastHistoryFetched);
if (L.isEnabled(L.PUMPCOMM)) if (L.isEnabled(L.PUMPCOMM))
log.debug("Loading event history from: " + new Date(lastHistoryFetched).toLocaleString()); log.debug("Loading event history from: " +DateUtil.dateAndTimeFullString(lastHistoryFetched));
} }
bleComm.sendMessage(msg); bleComm.sendMessage(msg);
while (!msg.done && bleComm.isConnected()) { while (!msg.done && bleComm.isConnected()) {

View file

@ -144,6 +144,16 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin {
return DanaRPump.getInstance().lastConnection > 0 && DanaRPump.getInstance().maxBasal > 0; return DanaRPump.getInstance().lastConnection > 0 && DanaRPump.getInstance().maxBasal > 0;
} }
@Override
public boolean isHandshakeInProgress() {
return sExecutionService != null && sExecutionService.isHandshakeInProgress();
}
@Override
public void finishHandshaking() {
sExecutionService.finishHandshaking();
}
@Override @Override
public void switchAllowed(ConfigBuilderFragment.PluginViewHolder.PluginSwitcher pluginSwitcher, FragmentActivity context) { public void switchAllowed(ConfigBuilderFragment.PluginViewHolder.PluginSwitcher pluginSwitcher, FragmentActivity context) {
boolean allowHardwarePump = SP.getBoolean("allow_hardware_pump", false); boolean allowHardwarePump = SP.getBoolean("allow_hardware_pump", false);

View file

@ -58,39 +58,26 @@ public class MsgHistoryEvents_v2 extends MessageBase {
return; return;
} }
Date datetime = dateTimeSecFromBuff(bytes, 1); // 6 bytes long datetime = dateTimeSecFromBuff(bytes, 1); // 6 bytes
int param1 = intFromBuff(bytes, 7, 2); int param1 = intFromBuff(bytes, 7, 2);
int param2 = intFromBuff(bytes, 9, 2); int param2 = intFromBuff(bytes, 9, 2);
TemporaryBasal temporaryBasal = new TemporaryBasal() TemporaryBasal temporaryBasal = new TemporaryBasal()
.date(datetime.getTime()) .date(datetime)
.source(Source.PUMP) .source(Source.PUMP)
.pumpId(datetime.getTime()); .pumpId(datetime);
ExtendedBolus extendedBolus = new ExtendedBolus(); ExtendedBolus extendedBolus = new ExtendedBolus();
extendedBolus.date = datetime.getTime(); extendedBolus.date = datetime;
extendedBolus.source = Source.PUMP; extendedBolus.source = Source.PUMP;
extendedBolus.pumpId = datetime.getTime(); extendedBolus.pumpId = datetime;
DetailedBolusInfo detailedBolusInfo = DetailedBolusInfoStorage.findDetailedBolusInfo(datetime.getTime());
if (detailedBolusInfo == null) {
if (L.isEnabled(L.PUMPCOMM))
log.debug("Detailed bolus info not found for " + datetime.toLocaleString());
detailedBolusInfo = new DetailedBolusInfo();
} else {
if (L.isEnabled(L.PUMPCOMM))
log.debug("Detailed bolus info found: " + detailedBolusInfo);
}
detailedBolusInfo.date = datetime.getTime();
detailedBolusInfo.source = Source.PUMP;
detailedBolusInfo.pumpId = datetime.getTime();
String status = ""; String status = "";
switch (recordCode) { switch (recordCode) {
case DanaRPump.TEMPSTART: case DanaRPump.TEMPSTART:
if (L.isEnabled(L.PUMPCOMM)) if (L.isEnabled(L.PUMPCOMM))
log.debug("EVENT TEMPSTART (" + recordCode + ") " + datetime.toLocaleString() + " Ratio: " + param1 + "% Duration: " + param2 + "min"); log.debug("EVENT TEMPSTART (" + recordCode + ") " + DateUtil.dateAndTimeFullString(datetime) + " (" + datetime + ")" + " Ratio: " + param1 + "% Duration: " + param2 + "min");
temporaryBasal.percentRate = param1; temporaryBasal.percentRate = param1;
temporaryBasal.durationInMinutes = param2; temporaryBasal.durationInMinutes = param2;
TreatmentsPlugin.getPlugin().addToHistoryTempBasal(temporaryBasal); TreatmentsPlugin.getPlugin().addToHistoryTempBasal(temporaryBasal);
@ -98,13 +85,13 @@ public class MsgHistoryEvents_v2 extends MessageBase {
break; break;
case DanaRPump.TEMPSTOP: case DanaRPump.TEMPSTOP:
if (L.isEnabled(L.PUMPCOMM)) if (L.isEnabled(L.PUMPCOMM))
log.debug("EVENT TEMPSTOP (" + recordCode + ") " + datetime.toLocaleString()); log.debug("EVENT TEMPSTOP (" + recordCode + ") " + DateUtil.dateAndTimeFullString(datetime));
TreatmentsPlugin.getPlugin().addToHistoryTempBasal(temporaryBasal); TreatmentsPlugin.getPlugin().addToHistoryTempBasal(temporaryBasal);
status = "TEMPSTOP " + DateUtil.timeString(datetime); status = "TEMPSTOP " + DateUtil.timeString(datetime);
break; break;
case DanaRPump.EXTENDEDSTART: case DanaRPump.EXTENDEDSTART:
if (L.isEnabled(L.PUMPCOMM)) if (L.isEnabled(L.PUMPCOMM))
log.debug("EVENT EXTENDEDSTART (" + recordCode + ") " + datetime.toLocaleString() + " Amount: " + (param1 / 100d) + "U Duration: " + param2 + "min"); log.debug("EVENT EXTENDEDSTART (" + recordCode + ") " + DateUtil.dateAndTimeFullString(datetime) + " (" + datetime + ")" + " Amount: " + (param1 / 100d) + "U Duration: " + param2 + "min");
extendedBolus.insulin = param1 / 100d; extendedBolus.insulin = param1 / 100d;
extendedBolus.durationInMinutes = param2; extendedBolus.durationInMinutes = param2;
TreatmentsPlugin.getPlugin().addToHistoryExtendedBolus(extendedBolus); TreatmentsPlugin.getPlugin().addToHistoryExtendedBolus(extendedBolus);
@ -112,29 +99,43 @@ public class MsgHistoryEvents_v2 extends MessageBase {
break; break;
case DanaRPump.EXTENDEDSTOP: case DanaRPump.EXTENDEDSTOP:
if (L.isEnabled(L.PUMPCOMM)) if (L.isEnabled(L.PUMPCOMM))
log.debug("EVENT EXTENDEDSTOP (" + recordCode + ") " + datetime.toLocaleString() + " Delivered: " + (param1 / 100d) + "U RealDuration: " + param2 + "min"); log.debug("EVENT EXTENDEDSTOP (" + recordCode + ") " + DateUtil.dateAndTimeFullString(datetime) + " (" + datetime + ")" + " Delivered: " + (param1 / 100d) + "U RealDuration: " + param2 + "min");
TreatmentsPlugin.getPlugin().addToHistoryExtendedBolus(extendedBolus); TreatmentsPlugin.getPlugin().addToHistoryExtendedBolus(extendedBolus);
status = "EXTENDEDSTOP " + DateUtil.timeString(datetime); status = "EXTENDEDSTOP " + DateUtil.timeString(datetime);
break; break;
case DanaRPump.BOLUS: case DanaRPump.BOLUS:
DetailedBolusInfo detailedBolusInfo = DetailedBolusInfoStorage.findDetailedBolusInfo(datetime);
if (detailedBolusInfo == null) {
detailedBolusInfo = new DetailedBolusInfo();
}
detailedBolusInfo.date = datetime;
detailedBolusInfo.source = Source.PUMP;
detailedBolusInfo.pumpId = datetime;
detailedBolusInfo.insulin = param1 / 100d; detailedBolusInfo.insulin = param1 / 100d;
boolean newRecord = TreatmentsPlugin.getPlugin().addToHistoryTreatment(detailedBolusInfo, false); boolean newRecord = TreatmentsPlugin.getPlugin().addToHistoryTreatment(detailedBolusInfo, false);
if (L.isEnabled(L.PUMPCOMM)) if (L.isEnabled(L.PUMPCOMM))
log.debug((newRecord ? "**NEW** " : "") + "EVENT BOLUS (" + recordCode + ") " + datetime.toLocaleString() + " Bolus: " + (param1 / 100d) + "U Duration: " + param2 + "min"); log.debug((newRecord ? "**NEW** " : "") + "EVENT BOLUS (" + recordCode + ") " + DateUtil.dateAndTimeFullString(datetime) + " (" + datetime + ")" + " Bolus: " + (param1 / 100d) + "U Duration: " + param2 + "min");
DetailedBolusInfoStorage.remove(detailedBolusInfo.date);
status = "BOLUS " + DateUtil.timeString(datetime); status = "BOLUS " + DateUtil.timeString(datetime);
break; break;
case DanaRPump.DUALBOLUS: case DanaRPump.DUALBOLUS:
detailedBolusInfo = DetailedBolusInfoStorage.findDetailedBolusInfo(datetime);
if (detailedBolusInfo == null) {
detailedBolusInfo = new DetailedBolusInfo();
}
detailedBolusInfo.date = datetime;
detailedBolusInfo.source = Source.PUMP;
detailedBolusInfo.pumpId = datetime;
detailedBolusInfo.insulin = param1 / 100d; detailedBolusInfo.insulin = param1 / 100d;
newRecord = TreatmentsPlugin.getPlugin().addToHistoryTreatment(detailedBolusInfo, false); newRecord = TreatmentsPlugin.getPlugin().addToHistoryTreatment(detailedBolusInfo, false);
if (L.isEnabled(L.PUMPCOMM)) if (L.isEnabled(L.PUMPCOMM))
log.debug((newRecord ? "**NEW** " : "") + "EVENT DUALBOLUS (" + recordCode + ") " + datetime.toLocaleString() + " Bolus: " + (param1 / 100d) + "U Duration: " + param2 + "min"); log.debug((newRecord ? "**NEW** " : "") + "EVENT DUALBOLUS (" + recordCode + ") " + DateUtil.dateAndTimeFullString(datetime) + " (" + datetime + ")" + " Bolus: " + (param1 / 100d) + "U Duration: " + param2 + "min");
DetailedBolusInfoStorage.remove(detailedBolusInfo.date);
status = "DUALBOLUS " + DateUtil.timeString(datetime); status = "DUALBOLUS " + DateUtil.timeString(datetime);
break; break;
case DanaRPump.DUALEXTENDEDSTART: case DanaRPump.DUALEXTENDEDSTART:
if (L.isEnabled(L.PUMPCOMM)) if (L.isEnabled(L.PUMPCOMM))
log.debug("EVENT DUALEXTENDEDSTART (" + recordCode + ") " + datetime.toLocaleString() + " Amount: " + (param1 / 100d) + "U Duration: " + param2 + "min"); log.debug("EVENT DUALEXTENDEDSTART (" + recordCode + ") " + DateUtil.dateAndTimeFullString(datetime) + " (" + datetime + ")" + " Amount: " + (param1 / 100d) + "U Duration: " + param2 + "min");
extendedBolus.insulin = param1 / 100d; extendedBolus.insulin = param1 / 100d;
extendedBolus.durationInMinutes = param2; extendedBolus.durationInMinutes = param2;
TreatmentsPlugin.getPlugin().addToHistoryExtendedBolus(extendedBolus); TreatmentsPlugin.getPlugin().addToHistoryExtendedBolus(extendedBolus);
@ -142,55 +143,55 @@ public class MsgHistoryEvents_v2 extends MessageBase {
break; break;
case DanaRPump.DUALEXTENDEDSTOP: case DanaRPump.DUALEXTENDEDSTOP:
if (L.isEnabled(L.PUMPCOMM)) if (L.isEnabled(L.PUMPCOMM))
log.debug("EVENT DUALEXTENDEDSTOP (" + recordCode + ") " + datetime.toLocaleString() + " Delivered: " + (param1 / 100d) + "U RealDuration: " + param2 + "min"); log.debug("EVENT DUALEXTENDEDSTOP (" + recordCode + ") " + DateUtil.dateAndTimeFullString(datetime) + " (" + datetime + ")" + " Delivered: " + (param1 / 100d) + "U RealDuration: " + param2 + "min");
TreatmentsPlugin.getPlugin().addToHistoryExtendedBolus(extendedBolus); TreatmentsPlugin.getPlugin().addToHistoryExtendedBolus(extendedBolus);
status = "DUALEXTENDEDSTOP " + DateUtil.timeString(datetime); status = "DUALEXTENDEDSTOP " + DateUtil.timeString(datetime);
break; break;
case DanaRPump.SUSPENDON: case DanaRPump.SUSPENDON:
if (L.isEnabled(L.PUMPCOMM)) if (L.isEnabled(L.PUMPCOMM))
log.debug("EVENT SUSPENDON (" + recordCode + ") " + datetime.toLocaleString()); log.debug("EVENT SUSPENDON (" + recordCode + ") " + DateUtil.dateAndTimeFullString(datetime) + " (" + datetime + ")");
status = "SUSPENDON " + DateUtil.timeString(datetime); status = "SUSPENDON " + DateUtil.timeString(datetime);
break; break;
case DanaRPump.SUSPENDOFF: case DanaRPump.SUSPENDOFF:
if (L.isEnabled(L.PUMPCOMM)) if (L.isEnabled(L.PUMPCOMM))
log.debug("EVENT SUSPENDOFF (" + recordCode + ") " + datetime.toLocaleString()); log.debug("EVENT SUSPENDOFF (" + recordCode + ") " + DateUtil.dateAndTimeFullString(datetime) + " (" + datetime + ")");
status = "SUSPENDOFF " + DateUtil.timeString(datetime); status = "SUSPENDOFF " + DateUtil.timeString(datetime);
break; break;
case DanaRPump.REFILL: case DanaRPump.REFILL:
if (L.isEnabled(L.PUMPCOMM)) if (L.isEnabled(L.PUMPCOMM))
log.debug("EVENT REFILL (" + recordCode + ") " + datetime.toLocaleString() + " Amount: " + param1 / 100d + "U"); log.debug("EVENT REFILL (" + recordCode + ") " + DateUtil.dateAndTimeFullString(datetime) + " (" + datetime + ")" + " Amount: " + param1 / 100d + "U");
status = "REFILL " + DateUtil.timeString(datetime); status = "REFILL " + DateUtil.timeString(datetime);
break; break;
case DanaRPump.PRIME: case DanaRPump.PRIME:
if (L.isEnabled(L.PUMPCOMM)) if (L.isEnabled(L.PUMPCOMM))
log.debug("EVENT PRIME (" + recordCode + ") " + datetime.toLocaleString() + " Amount: " + param1 / 100d + "U"); log.debug("EVENT PRIME (" + recordCode + ") " + DateUtil.dateAndTimeFullString(datetime) + " (" + datetime + ")" + " Amount: " + param1 / 100d + "U");
status = "PRIME " + DateUtil.timeString(datetime); status = "PRIME " + DateUtil.timeString(datetime);
break; break;
case DanaRPump.PROFILECHANGE: case DanaRPump.PROFILECHANGE:
if (L.isEnabled(L.PUMPCOMM)) if (L.isEnabled(L.PUMPCOMM))
log.debug("EVENT PROFILECHANGE (" + recordCode + ") " + datetime.toLocaleString() + " No: " + param1 + " CurrentRate: " + (param2 / 100d) + "U/h"); log.debug("EVENT PROFILECHANGE (" + recordCode + ") " + DateUtil.dateAndTimeFullString(datetime) + " (" + datetime + ")" + " No: " + param1 + " CurrentRate: " + (param2 / 100d) + "U/h");
status = "PROFILECHANGE " + DateUtil.timeString(datetime); status = "PROFILECHANGE " + DateUtil.timeString(datetime);
break; break;
case DanaRPump.CARBS: case DanaRPump.CARBS:
DetailedBolusInfo emptyCarbsInfo = new DetailedBolusInfo(); DetailedBolusInfo emptyCarbsInfo = new DetailedBolusInfo();
emptyCarbsInfo.carbs = param1; emptyCarbsInfo.carbs = param1;
emptyCarbsInfo.date = datetime.getTime(); emptyCarbsInfo.date = datetime;
emptyCarbsInfo.source = Source.PUMP; emptyCarbsInfo.source = Source.PUMP;
emptyCarbsInfo.pumpId = datetime.getTime(); emptyCarbsInfo.pumpId = datetime;
newRecord = TreatmentsPlugin.getPlugin().addToHistoryTreatment(emptyCarbsInfo, false); newRecord = TreatmentsPlugin.getPlugin().addToHistoryTreatment(emptyCarbsInfo, false);
if (L.isEnabled(L.PUMPCOMM)) if (L.isEnabled(L.PUMPCOMM))
log.debug((newRecord ? "**NEW** " : "") + "EVENT CARBS (" + recordCode + ") " + datetime.toLocaleString() + " Carbs: " + param1 + "g"); log.debug((newRecord ? "**NEW** " : "") + "EVENT CARBS (" + recordCode + ") " + DateUtil.dateAndTimeFullString(datetime) + " (" + datetime + ")" + " Carbs: " + param1 + "g");
status = "CARBS " + DateUtil.timeString(datetime); status = "CARBS " + DateUtil.timeString(datetime);
break; break;
default: default:
if (L.isEnabled(L.PUMPCOMM)) if (L.isEnabled(L.PUMPCOMM))
log.debug("Event: " + recordCode + " " + datetime.toLocaleString() + " Param1: " + param1 + " Param2: " + param2); log.debug("Event: " + recordCode + " " + DateUtil.dateAndTimeFullString(datetime) + " (" + datetime + ")" + " Param1: " + param1 + " Param2: " + param2);
status = "UNKNOWN " + DateUtil.timeString(datetime); status = "UNKNOWN " + DateUtil.timeString(datetime);
break; break;
} }
if (datetime.getTime() > lastEventTimeLoaded) if (datetime > lastEventTimeLoaded)
lastEventTimeLoaded = datetime.getTime(); lastEventTimeLoaded = datetime;
MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.processinghistory) + ": " + status)); MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.processinghistory) + ": " + status));
} }

View file

@ -5,8 +5,6 @@ import android.support.annotation.NonNull;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.Date;
import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump; import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump;
import info.nightscout.androidaps.plugins.PumpDanaR.comm.MessageBase; import info.nightscout.androidaps.plugins.PumpDanaR.comm.MessageBase;
@ -33,7 +31,7 @@ public class MsgStatusBolusExtended_v2 extends MessageBase {
int extendedBolusSoFarInMinutes = extendedBolusSoFarInSecs / 60; int extendedBolusSoFarInMinutes = extendedBolusSoFarInSecs / 60;
double extendedBolusAbsoluteRate = isExtendedInProgress ? extendedBolusAmount / extendedBolusMinutes * 60 : 0d; double extendedBolusAbsoluteRate = isExtendedInProgress ? extendedBolusAmount / extendedBolusMinutes * 60 : 0d;
Date extendedBolusStart = isExtendedInProgress ? getDateFromSecAgo(extendedBolusSoFarInSecs) : new Date(0); long extendedBolusStart = isExtendedInProgress ? getDateFromSecAgo(extendedBolusSoFarInSecs) : 0;
int extendedBolusRemainingMinutes = extendedBolusMinutes - extendedBolusSoFarInMinutes; int extendedBolusRemainingMinutes = extendedBolusMinutes - extendedBolusSoFarInMinutes;
DanaRPump pump = DanaRPump.getInstance(); DanaRPump pump = DanaRPump.getInstance();
@ -57,8 +55,8 @@ public class MsgStatusBolusExtended_v2 extends MessageBase {
} }
@NonNull @NonNull
private Date getDateFromSecAgo(int tempBasalAgoSecs) { private long getDateFromSecAgo(int tempBasalAgoSecs) {
return new Date((long) (Math.ceil(System.currentTimeMillis() / 1000d) - tempBasalAgoSecs) * 1000); return (long) (Math.ceil(System.currentTimeMillis() / 1000d) - tempBasalAgoSecs) * 1000;
} }
} }

View file

@ -5,11 +5,10 @@ import android.support.annotation.NonNull;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.Date;
import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump; import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump;
import info.nightscout.androidaps.plugins.PumpDanaR.comm.MessageBase; import info.nightscout.androidaps.plugins.PumpDanaR.comm.MessageBase;
import info.nightscout.utils.DateUtil;
public class MsgStatusTempBasal_v2 extends MessageBase { public class MsgStatusTempBasal_v2 extends MessageBase {
private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); private Logger log = LoggerFactory.getLogger(L.PUMPCOMM);
@ -31,7 +30,7 @@ public class MsgStatusTempBasal_v2 extends MessageBase {
else tempBasalTotalSec = intFromBuff(bytes, 2, 1) * 60 * 60; else tempBasalTotalSec = intFromBuff(bytes, 2, 1) * 60 * 60;
int tempBasalRunningSeconds = intFromBuff(bytes, 3, 3); int tempBasalRunningSeconds = intFromBuff(bytes, 3, 3);
int tempBasalRemainingMin = (tempBasalTotalSec - tempBasalRunningSeconds) / 60; int tempBasalRemainingMin = (tempBasalTotalSec - tempBasalRunningSeconds) / 60;
Date tempBasalStart = isTempBasalInProgress ? getDateFromTempBasalSecAgo(tempBasalRunningSeconds) : new Date(0); long tempBasalStart = isTempBasalInProgress ? getDateFromTempBasalSecAgo(tempBasalRunningSeconds) : 0;
DanaRPump pump = DanaRPump.getInstance(); DanaRPump pump = DanaRPump.getInstance();
pump.isTempBasalInProgress = isTempBasalInProgress; pump.isTempBasalInProgress = isTempBasalInProgress;
@ -46,13 +45,13 @@ public class MsgStatusTempBasal_v2 extends MessageBase {
log.debug("Current temp basal percent: " + tempBasalPercent); log.debug("Current temp basal percent: " + tempBasalPercent);
log.debug("Current temp basal remaining min: " + tempBasalRemainingMin); log.debug("Current temp basal remaining min: " + tempBasalRemainingMin);
log.debug("Current temp basal total sec: " + tempBasalTotalSec); log.debug("Current temp basal total sec: " + tempBasalTotalSec);
log.debug("Current temp basal start: " + tempBasalStart); log.debug("Current temp basal start: " + DateUtil.dateAndTimeFullString(tempBasalStart));
} }
} }
@NonNull @NonNull
private Date getDateFromTempBasalSecAgo(int tempBasalAgoSecs) { private long getDateFromTempBasalSecAgo(int tempBasalAgoSecs) {
return new Date((long) (Math.ceil(System.currentTimeMillis() / 1000d) - tempBasalAgoSecs) * 1000); return (long) (Math.ceil(System.currentTimeMillis() / 1000d) - tempBasalAgoSecs) * 1000;
} }
} }

View file

@ -133,35 +133,34 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService {
if (mConnectionInProgress) if (mConnectionInProgress)
return; return;
new Thread(new Runnable() { new Thread(() -> {
@Override mHandshakeInProgress = false;
public void run() { mConnectionInProgress = true;
mConnectionInProgress = true; getBTSocketForSelectedPump();
getBTSocketForSelectedPump(); if (mRfcommSocket == null || mBTDevice == null) {
if (mRfcommSocket == null || mBTDevice == null) {
mConnectionInProgress = false;
return; // Device not found
}
try {
mRfcommSocket.connect();
} catch (IOException e) {
//log.error("Unhandled exception", e);
if (e.getMessage().contains("socket closed")) {
log.error("Unhandled exception", e);
}
}
if (isConnected()) {
if (mSerialIOThread != null) {
mSerialIOThread.disconnect("Recreate SerialIOThread");
}
mSerialIOThread = new SerialIOThread(mRfcommSocket);
MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.CONNECTED, 0));
}
mConnectionInProgress = false; mConnectionInProgress = false;
return; // Device not found
} }
try {
mRfcommSocket.connect();
} catch (IOException e) {
//log.error("Unhandled exception", e);
if (e.getMessage().contains("socket closed")) {
log.error("Unhandled exception", e);
}
}
if (isConnected()) {
if (mSerialIOThread != null) {
mSerialIOThread.disconnect("Recreate SerialIOThread");
}
mSerialIOThread = new SerialIOThread(mRfcommSocket);
mHandshakeInProgress = true;
MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.HANDSHAKING, 0));
}
mConnectionInProgress = false;
}).start(); }).start();
} }
@ -203,7 +202,7 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService {
MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumptime))); MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumptime)));
mSerialIOThread.sendMessage(new MsgSettingPumpTime()); mSerialIOThread.sendMessage(new MsgSettingPumpTime());
long timeDiff = (mDanaRPump.pumpTime.getTime() - System.currentTimeMillis()) / 1000L; long timeDiff = (mDanaRPump.pumpTime - System.currentTimeMillis()) / 1000L;
if (L.isEnabled(L.PUMP)) if (L.isEnabled(L.PUMP))
log.debug("Pump time difference: " + timeDiff + " seconds"); log.debug("Pump time difference: " + timeDiff + " seconds");
if (Math.abs(timeDiff) > 3) { if (Math.abs(timeDiff) > 3) {
@ -228,7 +227,7 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService {
// add 10sec to be sure we are over minute (will be cutted off anyway) // add 10sec to be sure we are over minute (will be cutted off anyway)
mSerialIOThread.sendMessage(new MsgSetTime(new Date(DateUtil.now() + T.secs(10).msecs()))); mSerialIOThread.sendMessage(new MsgSetTime(new Date(DateUtil.now() + T.secs(10).msecs())));
mSerialIOThread.sendMessage(new MsgSettingPumpTime()); mSerialIOThread.sendMessage(new MsgSettingPumpTime());
timeDiff = (mDanaRPump.pumpTime.getTime() - System.currentTimeMillis()) / 1000L; timeDiff = (mDanaRPump.pumpTime - System.currentTimeMillis()) / 1000L;
if (L.isEnabled(L.PUMP)) if (L.isEnabled(L.PUMP))
log.debug("Pump time difference: " + timeDiff + " seconds"); log.debug("Pump time difference: " + timeDiff + " seconds");
} }
@ -269,7 +268,6 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService {
} catch (Exception e) { } catch (Exception e) {
log.error("Unhandled exception", e); log.error("Unhandled exception", e);
} }
return;
} }
public boolean tempBasal(int percent, int durationInHours) { public boolean tempBasal(int percent, int durationInHours) {
@ -479,7 +477,7 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService {
} else { } else {
msg = new MsgHistoryEvents_v2(lastHistoryFetched); msg = new MsgHistoryEvents_v2(lastHistoryFetched);
if (L.isEnabled(L.PUMP)) if (L.isEnabled(L.PUMP))
log.debug("Loading event history from: " + new Date(lastHistoryFetched).toLocaleString()); log.debug("Loading event history from: " + DateUtil.dateAndTimeFullString(lastHistoryFetched));
} }
mSerialIOThread.sendMessage(msg); mSerialIOThread.sendMessage(msg);
while (!msg.done && mRfcommSocket.isConnected()) { while (!msg.done && mRfcommSocket.isConnected()) {

View file

@ -103,7 +103,7 @@ public class InsightPlugin extends PluginBase implements PumpInterface, Constrai
private static Logger log = LoggerFactory.getLogger(InsightPlugin.class); 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 Date lastDataTime = new Date(0); private long lastDataTime = 0;
private boolean fauxTBRcancel = true; private boolean fauxTBRcancel = true;
private PumpDescription pumpDescription = new PumpDescription(); private PumpDescription pumpDescription = new PumpDescription();
private double basalRate = 0; private double basalRate = 0;
@ -259,6 +259,15 @@ public class InsightPlugin extends PluginBase implements PumpInterface, Constrai
return Connector.get().isPumpConnecting(); return Connector.get().isPumpConnecting();
} }
@Override
public boolean isHandshakeInProgress() {
return false;
}
@Override
public void finishHandshaking() {
}
@Override @Override
public void connect(String reason) { public void connect(String reason) {
log("InsightPlugin::connect()"); log("InsightPlugin::connect()");
@ -407,7 +416,7 @@ public class InsightPlugin extends PluginBase implements PumpInterface, Constrai
} }
@Override @Override
public Date lastDataTime() { public long lastDataTime() {
return lastDataTime; return lastDataTime;
} }
@ -877,7 +886,7 @@ public class InsightPlugin extends PluginBase implements PumpInterface, Constrai
private <T> T fetchTaskRunner(TaskRunner taskRunner, Class<T> resultType) throws Exception { private <T> T fetchTaskRunner(TaskRunner taskRunner, Class<T> resultType) throws Exception {
try { try {
T result = (T) taskRunner.fetchAndWaitUsingLatch(BUSY_WAIT_TIME); T result = (T) taskRunner.fetchAndWaitUsingLatch(BUSY_WAIT_TIME);
lastDataTime = new Date(); 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 while fetching " + taskRunner.getClass().getSimpleName() + ": " + e.getClass().getSimpleName());
@ -888,7 +897,7 @@ public class InsightPlugin extends PluginBase implements PumpInterface, Constrai
private <T extends AppLayerMessage> T fetchSingleMessage(AppLayerMessage message, Class<T> resultType) throws Exception { private <T extends AppLayerMessage> T fetchSingleMessage(AppLayerMessage message, Class<T> resultType) throws Exception {
try { try {
T result = (T) new SingleMessageTaskRunner(connector.getServiceConnector(), message).fetchAndWaitUsingLatch(BUSY_WAIT_TIME); T result = (T) new SingleMessageTaskRunner(connector.getServiceConnector(), message).fetchAndWaitUsingLatch(BUSY_WAIT_TIME);
lastDataTime = new Date(); 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 while fetching " + message.getClass().getSimpleName() + ": " + e.getClass().getSimpleName());

View file

@ -5,8 +5,6 @@ import org.json.JSONObject;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.Date;
import info.nightscout.androidaps.BuildConfig; import info.nightscout.androidaps.BuildConfig;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
@ -90,6 +88,15 @@ public class MDIPlugin extends PluginBase implements PumpInterface {
return false; return false;
} }
@Override
public boolean isHandshakeInProgress() {
return false;
}
@Override
public void finishHandshaking() {
}
@Override @Override
public void connect(String reason) { public void connect(String reason) {
} }
@ -120,8 +127,8 @@ public class MDIPlugin extends PluginBase implements PumpInterface {
} }
@Override @Override
public Date lastDataTime() { public long lastDataTime() {
return new Date(); return System.currentTimeMillis();
} }
@Override @Override

View file

@ -7,8 +7,6 @@ import org.json.JSONObject;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.Date;
import info.nightscout.androidaps.BuildConfig; import info.nightscout.androidaps.BuildConfig;
import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
@ -53,7 +51,7 @@ public class VirtualPumpPlugin extends PluginBase implements PumpInterface {
static Integer batteryPercent = 50; static Integer batteryPercent = 50;
static Integer reservoirInUnits = 50; static Integer reservoirInUnits = 50;
private Date lastDataTime = new Date(0); private long lastDataTime = 0;
private static boolean fromNSAreCommingFakedExtendedBoluses = false; private static boolean fromNSAreCommingFakedExtendedBoluses = false;
@ -149,11 +147,20 @@ public class VirtualPumpPlugin extends PluginBase implements PumpInterface {
return false; return false;
} }
@Override
public boolean isHandshakeInProgress() {
return false;
}
@Override
public void finishHandshaking() {
}
@Override @Override
public void connect(String reason) { public void connect(String reason) {
if (!Config.NSCLIENT) if (!Config.NSCLIENT)
NSUpload.uploadDeviceStatus(); NSUpload.uploadDeviceStatus();
lastDataTime = new Date(); lastDataTime = System.currentTimeMillis();
} }
@Override @Override
@ -166,12 +173,12 @@ public class VirtualPumpPlugin extends PluginBase implements PumpInterface {
@Override @Override
public void getPumpStatus() { public void getPumpStatus() {
lastDataTime = new Date(); lastDataTime = System.currentTimeMillis();
} }
@Override @Override
public PumpEnactResult setNewBasalProfile(Profile profile) { public PumpEnactResult setNewBasalProfile(Profile profile) {
lastDataTime = new Date(); lastDataTime = System.currentTimeMillis();
// Do nothing here. we are using MainApp.getConfigBuilder().getActiveProfile().getProfile(); // Do nothing here. we are using MainApp.getConfigBuilder().getActiveProfile().getProfile();
PumpEnactResult result = new PumpEnactResult(); PumpEnactResult result = new PumpEnactResult();
result.success = true; result.success = true;
@ -186,7 +193,7 @@ public class VirtualPumpPlugin extends PluginBase implements PumpInterface {
} }
@Override @Override
public Date lastDataTime() { public long lastDataTime() {
return lastDataTime; return lastDataTime;
} }
@ -227,7 +234,7 @@ public class VirtualPumpPlugin extends PluginBase implements PumpInterface {
if (L.isEnabled(L.PUMPCOMM)) if (L.isEnabled(L.PUMPCOMM))
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);
MainApp.bus().post(new EventVirtualPumpUpdateGui()); MainApp.bus().post(new EventVirtualPumpUpdateGui());
lastDataTime = new Date(); lastDataTime = System.currentTimeMillis();
TreatmentsPlugin.getPlugin().addToHistoryTreatment(detailedBolusInfo, false); TreatmentsPlugin.getPlugin().addToHistoryTreatment(detailedBolusInfo, false);
return result; return result;
} }
@ -255,7 +262,7 @@ public class VirtualPumpPlugin extends PluginBase implements PumpInterface {
if (L.isEnabled(L.PUMPCOMM)) if (L.isEnabled(L.PUMPCOMM))
log.debug("Setting temp basal absolute: " + result); log.debug("Setting temp basal absolute: " + result);
MainApp.bus().post(new EventVirtualPumpUpdateGui()); MainApp.bus().post(new EventVirtualPumpUpdateGui());
lastDataTime = new Date(); lastDataTime = System.currentTimeMillis();
return result; return result;
} }
@ -283,7 +290,7 @@ public class VirtualPumpPlugin extends PluginBase implements PumpInterface {
if (L.isEnabled(L.PUMPCOMM)) if (L.isEnabled(L.PUMPCOMM))
log.debug("Settings temp basal percent: " + result); log.debug("Settings temp basal percent: " + result);
MainApp.bus().post(new EventVirtualPumpUpdateGui()); MainApp.bus().post(new EventVirtualPumpUpdateGui());
lastDataTime = new Date(); lastDataTime = System.currentTimeMillis();
return result; return result;
} }
@ -307,7 +314,7 @@ public class VirtualPumpPlugin extends PluginBase implements PumpInterface {
if (L.isEnabled(L.PUMPCOMM)) if (L.isEnabled(L.PUMPCOMM))
log.debug("Setting extended bolus: " + result); log.debug("Setting extended bolus: " + result);
MainApp.bus().post(new EventVirtualPumpUpdateGui()); MainApp.bus().post(new EventVirtualPumpUpdateGui());
lastDataTime = new Date(); lastDataTime = System.currentTimeMillis();
return result; return result;
} }
@ -326,7 +333,7 @@ public class VirtualPumpPlugin extends PluginBase implements PumpInterface {
log.debug("Canceling temp basal: " + result); log.debug("Canceling temp basal: " + result);
MainApp.bus().post(new EventVirtualPumpUpdateGui()); MainApp.bus().post(new EventVirtualPumpUpdateGui());
} }
lastDataTime = new Date(); lastDataTime = System.currentTimeMillis();
return result; return result;
} }
@ -345,7 +352,7 @@ public class VirtualPumpPlugin extends PluginBase implements PumpInterface {
if (L.isEnabled(L.PUMPCOMM)) if (L.isEnabled(L.PUMPCOMM))
log.debug("Canceling extended bolus: " + result); log.debug("Canceling extended bolus: " + result);
MainApp.bus().post(new EventVirtualPumpUpdateGui()); MainApp.bus().post(new EventVirtualPumpUpdateGui());
lastDataTime = new Date(); lastDataTime = System.currentTimeMillis();
return result; return result;
} }

View file

@ -68,7 +68,7 @@ public class SmsCommunicatorFragment extends SubscriberFragment {
public void run() { public void run() {
class CustomComparator implements Comparator<SmsCommunicatorPlugin.Sms> { class CustomComparator implements Comparator<SmsCommunicatorPlugin.Sms> {
public int compare(SmsCommunicatorPlugin.Sms object1, SmsCommunicatorPlugin.Sms object2) { public int compare(SmsCommunicatorPlugin.Sms object1, SmsCommunicatorPlugin.Sms object2) {
return (int) (object1.date.getTime() - object2.date.getTime()); return (int) (object1.date - object2.date);
} }
} }
Collections.sort(SmsCommunicatorPlugin.getPlugin().messages, new CustomComparator()); Collections.sort(SmsCommunicatorPlugin.getPlugin().messages, new CustomComparator());

View file

@ -73,7 +73,7 @@ public class SmsCommunicatorPlugin extends PluginBase {
class Sms { class Sms {
String phoneNumber; String phoneNumber;
String text; String text;
Date date; long date;
boolean received = false; boolean received = false;
boolean sent = false; boolean sent = false;
boolean processed = false; boolean processed = false;
@ -87,18 +87,18 @@ public class SmsCommunicatorPlugin extends PluginBase {
Sms(SmsMessage message) { Sms(SmsMessage message) {
phoneNumber = message.getOriginatingAddress(); phoneNumber = message.getOriginatingAddress();
text = message.getMessageBody(); text = message.getMessageBody();
date = new Date(message.getTimestampMillis()); date = message.getTimestampMillis();
received = true; received = true;
} }
Sms(String phoneNumber, String text, Date date) { Sms(String phoneNumber, String text, long date) {
this.phoneNumber = phoneNumber; this.phoneNumber = phoneNumber;
this.text = text; this.text = text;
this.date = date; this.date = date;
sent = true; sent = true;
} }
Sms(String phoneNumber, String text, Date date, String confirmCode) { Sms(String phoneNumber, String text, long date, String confirmCode) {
this.phoneNumber = phoneNumber; this.phoneNumber = phoneNumber;
this.text = text; this.text = text;
this.date = date; this.date = date;
@ -230,7 +230,7 @@ public class SmsCommunicatorPlugin extends PluginBase {
+ MainApp.gs(R.string.sms_bolus) + " " + DecimalFormatter.to2Decimal(bolusIob.iob) + "U " + MainApp.gs(R.string.sms_bolus) + " " + DecimalFormatter.to2Decimal(bolusIob.iob) + "U "
+ MainApp.gs(R.string.sms_basal) + " " + DecimalFormatter.to2Decimal(basalIob.basaliob) + "U)"; + MainApp.gs(R.string.sms_basal) + " " + DecimalFormatter.to2Decimal(basalIob.basaliob) + "U)";
sendSMS(new Sms(receivedSms.phoneNumber, reply, new Date())); sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
receivedSms.processed = true; receivedSms.processed = true;
FabricPrivacy.getInstance().logCustom(new CustomEvent("SMS_Bg")); FabricPrivacy.getInstance().logCustom(new CustomEvent("SMS_Bg"));
break; break;
@ -248,7 +248,7 @@ public class SmsCommunicatorPlugin extends PluginBase {
MainApp.bus().post(new EventRefreshOverview("SMS_LOOP_STOP")); MainApp.bus().post(new EventRefreshOverview("SMS_LOOP_STOP"));
String reply = MainApp.gs(R.string.smscommunicator_loophasbeendisabled) + " " + String reply = MainApp.gs(R.string.smscommunicator_loophasbeendisabled) + " " +
MainApp.gs(result.success ? R.string.smscommunicator_tempbasalcanceled : R.string.smscommunicator_tempbasalcancelfailed); MainApp.gs(result.success ? R.string.smscommunicator_tempbasalcanceled : R.string.smscommunicator_tempbasalcancelfailed);
sendSMS(new Sms(receivedSms.phoneNumber, reply, new Date())); sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
} }
}); });
} }
@ -261,7 +261,7 @@ public class SmsCommunicatorPlugin extends PluginBase {
if (loopPlugin != null && !loopPlugin.isEnabled(PluginType.LOOP)) { if (loopPlugin != null && !loopPlugin.isEnabled(PluginType.LOOP)) {
loopPlugin.setPluginEnabled(PluginType.LOOP, true); loopPlugin.setPluginEnabled(PluginType.LOOP, true);
reply = MainApp.gs(R.string.smscommunicator_loophasbeenenabled); reply = MainApp.gs(R.string.smscommunicator_loophasbeenenabled);
sendSMS(new Sms(receivedSms.phoneNumber, reply, new Date())); sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
MainApp.bus().post(new EventRefreshOverview("SMS_LOOP_START")); MainApp.bus().post(new EventRefreshOverview("SMS_LOOP_START"));
} }
receivedSms.processed = true; receivedSms.processed = true;
@ -278,7 +278,7 @@ public class SmsCommunicatorPlugin extends PluginBase {
} else { } else {
reply = MainApp.gs(R.string.smscommunicator_loopisdisabled); reply = MainApp.gs(R.string.smscommunicator_loopisdisabled);
} }
sendSMS(new Sms(receivedSms.phoneNumber, reply, new Date())); sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
} }
receivedSms.processed = true; receivedSms.processed = true;
FabricPrivacy.getInstance().logCustom(new CustomEvent("SMS_Loop_Status")); FabricPrivacy.getInstance().logCustom(new CustomEvent("SMS_Loop_Status"));
@ -288,7 +288,7 @@ public class SmsCommunicatorPlugin extends PluginBase {
MainApp.bus().post(new EventRefreshOverview("SMS_LOOP_RESUME")); MainApp.bus().post(new EventRefreshOverview("SMS_LOOP_RESUME"));
NSUpload.uploadOpenAPSOffline(0); NSUpload.uploadOpenAPSOffline(0);
reply = MainApp.gs(R.string.smscommunicator_loopresumed); reply = MainApp.gs(R.string.smscommunicator_loopresumed);
sendSMSToAllNumbers(new Sms(receivedSms.phoneNumber, reply, new Date())); sendSMSToAllNumbers(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
FabricPrivacy.getInstance().logCustom(new CustomEvent("SMS_Loop_Resume")); FabricPrivacy.getInstance().logCustom(new CustomEvent("SMS_Loop_Resume"));
break; break;
case "SUSPEND": case "SUSPEND":
@ -298,18 +298,18 @@ public class SmsCommunicatorPlugin extends PluginBase {
duration = Math.min(180, duration); duration = Math.min(180, duration);
if (duration == 0) { if (duration == 0) {
reply = MainApp.gs(R.string.smscommunicator_wrongduration); reply = MainApp.gs(R.string.smscommunicator_wrongduration);
sendSMS(new Sms(receivedSms.phoneNumber, reply, new Date())); sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
} else if (remoteCommandsAllowed) { } else if (remoteCommandsAllowed) {
passCode = generatePasscode(); passCode = generatePasscode();
reply = String.format(MainApp.gs(R.string.smscommunicator_suspendreplywithcode), duration, passCode); reply = String.format(MainApp.gs(R.string.smscommunicator_suspendreplywithcode), duration, passCode);
receivedSms.processed = true; receivedSms.processed = true;
resetWaitingMessages(); resetWaitingMessages();
sendSMS(suspendWaitingForConfirmation = new Sms(receivedSms.phoneNumber, reply, new Date(), passCode)); sendSMS(suspendWaitingForConfirmation = new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis(), passCode));
suspendWaitingForConfirmation.duration = duration; suspendWaitingForConfirmation.duration = duration;
FabricPrivacy.getInstance().logCustom(new CustomEvent("SMS_Loop_Suspend")); FabricPrivacy.getInstance().logCustom(new CustomEvent("SMS_Loop_Suspend"));
} else { } else {
reply = MainApp.gs(R.string.smscommunicator_remotecommandnotallowed); reply = MainApp.gs(R.string.smscommunicator_remotecommandnotallowed);
sendSMS(new Sms(receivedSms.phoneNumber, reply, new Date())); sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
} }
break; break;
} }
@ -323,7 +323,7 @@ public class SmsCommunicatorPlugin extends PluginBase {
MainApp.instance().getApplicationContext().sendBroadcast(restartNSClient); MainApp.instance().getApplicationContext().sendBroadcast(restartNSClient);
List<ResolveInfo> q = MainApp.instance().getApplicationContext().getPackageManager().queryBroadcastReceivers(restartNSClient, 0); List<ResolveInfo> q = MainApp.instance().getApplicationContext().getPackageManager().queryBroadcastReceivers(restartNSClient, 0);
reply = "TERATMENTS REFRESH " + q.size() + " receivers"; reply = "TERATMENTS REFRESH " + q.size() + " receivers";
sendSMS(new Sms(receivedSms.phoneNumber, reply, new Date())); sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
receivedSms.processed = true; receivedSms.processed = true;
FabricPrivacy.getInstance().logCustom(new CustomEvent("SMS_Treatments_Refresh")); FabricPrivacy.getInstance().logCustom(new CustomEvent("SMS_Treatments_Refresh"));
break; break;
@ -337,7 +337,7 @@ public class SmsCommunicatorPlugin extends PluginBase {
MainApp.instance().getApplicationContext().sendBroadcast(restartNSClient); MainApp.instance().getApplicationContext().sendBroadcast(restartNSClient);
List<ResolveInfo> q = MainApp.instance().getApplicationContext().getPackageManager().queryBroadcastReceivers(restartNSClient, 0); List<ResolveInfo> q = MainApp.instance().getApplicationContext().getPackageManager().queryBroadcastReceivers(restartNSClient, 0);
reply = "NSCLIENT RESTART " + q.size() + " receivers"; reply = "NSCLIENT RESTART " + q.size() + " receivers";
sendSMS(new Sms(receivedSms.phoneNumber, reply, new Date())); sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
receivedSms.processed = true; receivedSms.processed = true;
FabricPrivacy.getInstance().logCustom(new CustomEvent("SMS_Nsclient_Restart")); FabricPrivacy.getInstance().logCustom(new CustomEvent("SMS_Nsclient_Restart"));
break; break;
@ -352,11 +352,11 @@ public class SmsCommunicatorPlugin extends PluginBase {
if (result.success) { if (result.success) {
if (pump != null) { if (pump != null) {
String reply = pump.shortStatus(true); String reply = pump.shortStatus(true);
sendSMSToAllNumbers(new Sms(receivedSms.phoneNumber, reply, new Date())); sendSMSToAllNumbers(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
} }
} else { } else {
String reply = MainApp.gs(R.string.readstatusfailed); String reply = MainApp.gs(R.string.readstatusfailed);
sendSMS(new Sms(receivedSms.phoneNumber, reply, new Date())); sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
} }
} }
}); });
@ -371,18 +371,18 @@ public class SmsCommunicatorPlugin extends PluginBase {
reply = String.format(MainApp.gs(R.string.smscommunicator_basalstopreplywithcode), passCode); reply = String.format(MainApp.gs(R.string.smscommunicator_basalstopreplywithcode), passCode);
receivedSms.processed = true; receivedSms.processed = true;
resetWaitingMessages(); resetWaitingMessages();
sendSMS(cancelTempBasalWaitingForConfirmation = new Sms(receivedSms.phoneNumber, reply, new Date(), passCode)); sendSMS(cancelTempBasalWaitingForConfirmation = new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis(), passCode));
FabricPrivacy.getInstance().logCustom(new CustomEvent("SMS_Basal")); FabricPrivacy.getInstance().logCustom(new CustomEvent("SMS_Basal"));
} else { } else {
reply = MainApp.gs(R.string.smscommunicator_remotebasalnotallowed); reply = MainApp.gs(R.string.smscommunicator_remotebasalnotallowed);
sendSMS(new Sms(receivedSms.phoneNumber, reply, new Date())); sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
} }
} else { } else {
tempBasal = SafeParse.stringToDouble(splited[1]); tempBasal = SafeParse.stringToDouble(splited[1]);
Profile profile = ProfileFunctions.getInstance().getProfile(); Profile profile = ProfileFunctions.getInstance().getProfile();
if (profile == null) { if (profile == null) {
reply = MainApp.gs(R.string.noprofile); reply = MainApp.gs(R.string.noprofile);
sendSMS(new Sms(receivedSms.phoneNumber, reply, new Date())); sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
} else { } else {
tempBasal = MainApp.getConstraintChecker().applyBasalConstraints(new Constraint<>(tempBasal), profile).value(); tempBasal = MainApp.getConstraintChecker().applyBasalConstraints(new Constraint<>(tempBasal), profile).value();
if (remoteCommandsAllowed) { if (remoteCommandsAllowed) {
@ -390,12 +390,12 @@ public class SmsCommunicatorPlugin extends PluginBase {
reply = String.format(MainApp.gs(R.string.smscommunicator_basalreplywithcode), tempBasal, passCode); reply = String.format(MainApp.gs(R.string.smscommunicator_basalreplywithcode), tempBasal, passCode);
receivedSms.processed = true; receivedSms.processed = true;
resetWaitingMessages(); resetWaitingMessages();
sendSMS(tempBasalWaitingForConfirmation = new Sms(receivedSms.phoneNumber, reply, new Date(), passCode)); sendSMS(tempBasalWaitingForConfirmation = new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis(), passCode));
tempBasalWaitingForConfirmation.tempBasal = tempBasal; tempBasalWaitingForConfirmation.tempBasal = tempBasal;
FabricPrivacy.getInstance().logCustom(new CustomEvent("SMS_Basal")); FabricPrivacy.getInstance().logCustom(new CustomEvent("SMS_Basal"));
} else { } else {
reply = MainApp.gs(R.string.smscommunicator_remotebasalnotallowed); reply = MainApp.gs(R.string.smscommunicator_remotebasalnotallowed);
sendSMS(new Sms(receivedSms.phoneNumber, reply, new Date())); sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
} }
} }
} }
@ -404,10 +404,10 @@ public class SmsCommunicatorPlugin extends PluginBase {
case "BOLUS": case "BOLUS":
if (System.currentTimeMillis() - lastRemoteBolusTime.getTime() < Constants.remoteBolusMinDistance) { if (System.currentTimeMillis() - lastRemoteBolusTime.getTime() < Constants.remoteBolusMinDistance) {
reply = MainApp.gs(R.string.smscommunicator_remotebolusnotallowed); reply = MainApp.gs(R.string.smscommunicator_remotebolusnotallowed);
sendSMS(new Sms(receivedSms.phoneNumber, reply, new Date())); sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
} else if (ConfigBuilderPlugin.getActivePump().isSuspended()) { } else if (ConfigBuilderPlugin.getActivePump().isSuspended()) {
reply = MainApp.gs(R.string.pumpsuspended); reply = MainApp.gs(R.string.pumpsuspended);
sendSMS(new Sms(receivedSms.phoneNumber, reply, new Date())); sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
} else if (splited.length > 1) { } else if (splited.length > 1) {
amount = SafeParse.stringToDouble(splited[1]); amount = SafeParse.stringToDouble(splited[1]);
amount = MainApp.getConstraintChecker().applyBolusConstraints(new Constraint<>(amount)).value(); amount = MainApp.getConstraintChecker().applyBolusConstraints(new Constraint<>(amount)).value();
@ -416,12 +416,12 @@ public class SmsCommunicatorPlugin extends PluginBase {
reply = String.format(MainApp.gs(R.string.smscommunicator_bolusreplywithcode), amount, passCode); reply = String.format(MainApp.gs(R.string.smscommunicator_bolusreplywithcode), amount, passCode);
receivedSms.processed = true; receivedSms.processed = true;
resetWaitingMessages(); resetWaitingMessages();
sendSMS(bolusWaitingForConfirmation = new Sms(receivedSms.phoneNumber, reply, new Date(), passCode)); sendSMS(bolusWaitingForConfirmation = new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis(), passCode));
bolusWaitingForConfirmation.bolusRequested = amount; bolusWaitingForConfirmation.bolusRequested = amount;
FabricPrivacy.getInstance().logCustom(new CustomEvent("SMS_Bolus")); FabricPrivacy.getInstance().logCustom(new CustomEvent("SMS_Bolus"));
} else { } else {
reply = MainApp.gs(R.string.smscommunicator_remotebolusnotallowed); reply = MainApp.gs(R.string.smscommunicator_remotebolusnotallowed);
sendSMS(new Sms(receivedSms.phoneNumber, reply, new Date())); sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
} }
} }
break; break;
@ -433,18 +433,18 @@ public class SmsCommunicatorPlugin extends PluginBase {
reply = String.format(MainApp.gs(R.string.smscommunicator_calibrationreplywithcode), amount, passCode); reply = String.format(MainApp.gs(R.string.smscommunicator_calibrationreplywithcode), amount, passCode);
receivedSms.processed = true; receivedSms.processed = true;
resetWaitingMessages(); resetWaitingMessages();
sendSMS(calibrationWaitingForConfirmation = new Sms(receivedSms.phoneNumber, reply, new Date(), passCode)); sendSMS(calibrationWaitingForConfirmation = new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis(), passCode));
calibrationWaitingForConfirmation.calibrationRequested = amount; calibrationWaitingForConfirmation.calibrationRequested = amount;
FabricPrivacy.getInstance().logCustom(new CustomEvent("SMS_Cal")); FabricPrivacy.getInstance().logCustom(new CustomEvent("SMS_Cal"));
} else { } else {
reply = MainApp.gs(R.string.smscommunicator_remotecalibrationnotallowed); reply = MainApp.gs(R.string.smscommunicator_remotecalibrationnotallowed);
sendSMS(new Sms(receivedSms.phoneNumber, reply, new Date())); sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
} }
} }
break; break;
default: // expect passCode here default: // expect passCode here
if (bolusWaitingForConfirmation != null && !bolusWaitingForConfirmation.processed && if (bolusWaitingForConfirmation != null && !bolusWaitingForConfirmation.processed &&
bolusWaitingForConfirmation.confirmCode.equals(splited[0]) && System.currentTimeMillis() - bolusWaitingForConfirmation.date.getTime() < Constants.SMS_CONFIRM_TIMEOUT) { bolusWaitingForConfirmation.confirmCode.equals(splited[0]) && System.currentTimeMillis() - bolusWaitingForConfirmation.date < Constants.SMS_CONFIRM_TIMEOUT) {
bolusWaitingForConfirmation.processed = true; bolusWaitingForConfirmation.processed = true;
DetailedBolusInfo detailedBolusInfo = new DetailedBolusInfo(); DetailedBolusInfo detailedBolusInfo = new DetailedBolusInfo();
detailedBolusInfo.insulin = bolusWaitingForConfirmation.bolusRequested; detailedBolusInfo.insulin = bolusWaitingForConfirmation.bolusRequested;
@ -459,18 +459,18 @@ public class SmsCommunicatorPlugin extends PluginBase {
if (pump != null) if (pump != null)
reply += "\n" + pump.shortStatus(true); reply += "\n" + pump.shortStatus(true);
lastRemoteBolusTime = new Date(); lastRemoteBolusTime = new Date();
sendSMSToAllNumbers(new Sms(receivedSms.phoneNumber, reply, new Date())); sendSMSToAllNumbers(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
} else { } else {
SystemClock.sleep(T.secs(60).msecs()); // wait some time to get history SystemClock.sleep(T.secs(60).msecs()); // wait some time to get history
String reply = MainApp.gs(R.string.smscommunicator_bolusfailed); String reply = MainApp.gs(R.string.smscommunicator_bolusfailed);
if (pump != null) if (pump != null)
reply += "\n" + pump.shortStatus(true); reply += "\n" + pump.shortStatus(true);
sendSMS(new Sms(receivedSms.phoneNumber, reply, new Date())); sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
} }
} }
}); });
} else if (tempBasalWaitingForConfirmation != null && !tempBasalWaitingForConfirmation.processed && } else if (tempBasalWaitingForConfirmation != null && !tempBasalWaitingForConfirmation.processed &&
tempBasalWaitingForConfirmation.confirmCode.equals(splited[0]) && System.currentTimeMillis() - tempBasalWaitingForConfirmation.date.getTime() < Constants.SMS_CONFIRM_TIMEOUT) { tempBasalWaitingForConfirmation.confirmCode.equals(splited[0]) && System.currentTimeMillis() - tempBasalWaitingForConfirmation.date < Constants.SMS_CONFIRM_TIMEOUT) {
tempBasalWaitingForConfirmation.processed = true; tempBasalWaitingForConfirmation.processed = true;
Profile profile = ProfileFunctions.getInstance().getProfile(); Profile profile = ProfileFunctions.getInstance().getProfile();
if (profile != null) if (profile != null)
@ -480,16 +480,16 @@ public class SmsCommunicatorPlugin extends PluginBase {
if (result.success) { if (result.success) {
String reply = String.format(MainApp.gs(R.string.smscommunicator_tempbasalset), result.absolute, result.duration); String reply = String.format(MainApp.gs(R.string.smscommunicator_tempbasalset), result.absolute, result.duration);
reply += "\n" + ConfigBuilderPlugin.getActivePump().shortStatus(true); reply += "\n" + ConfigBuilderPlugin.getActivePump().shortStatus(true);
sendSMSToAllNumbers(new Sms(receivedSms.phoneNumber, reply, new Date())); sendSMSToAllNumbers(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
} else { } else {
String reply = MainApp.gs(R.string.smscommunicator_tempbasalfailed); String reply = MainApp.gs(R.string.smscommunicator_tempbasalfailed);
reply += "\n" + ConfigBuilderPlugin.getActivePump().shortStatus(true); reply += "\n" + ConfigBuilderPlugin.getActivePump().shortStatus(true);
sendSMS(new Sms(receivedSms.phoneNumber, reply, new Date())); sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
} }
} }
}); });
} else if (cancelTempBasalWaitingForConfirmation != null && !cancelTempBasalWaitingForConfirmation.processed && } else if (cancelTempBasalWaitingForConfirmation != null && !cancelTempBasalWaitingForConfirmation.processed &&
cancelTempBasalWaitingForConfirmation.confirmCode.equals(splited[0]) && System.currentTimeMillis() - cancelTempBasalWaitingForConfirmation.date.getTime() < Constants.SMS_CONFIRM_TIMEOUT) { cancelTempBasalWaitingForConfirmation.confirmCode.equals(splited[0]) && System.currentTimeMillis() - cancelTempBasalWaitingForConfirmation.date < Constants.SMS_CONFIRM_TIMEOUT) {
cancelTempBasalWaitingForConfirmation.processed = true; cancelTempBasalWaitingForConfirmation.processed = true;
ConfigBuilderPlugin.getCommandQueue().cancelTempBasal(true, new Callback() { ConfigBuilderPlugin.getCommandQueue().cancelTempBasal(true, new Callback() {
@Override @Override
@ -497,27 +497,27 @@ public class SmsCommunicatorPlugin extends PluginBase {
if (result.success) { if (result.success) {
String reply = MainApp.gs(R.string.smscommunicator_tempbasalcanceled); String reply = MainApp.gs(R.string.smscommunicator_tempbasalcanceled);
reply += "\n" + ConfigBuilderPlugin.getActivePump().shortStatus(true); reply += "\n" + ConfigBuilderPlugin.getActivePump().shortStatus(true);
sendSMSToAllNumbers(new Sms(receivedSms.phoneNumber, reply, new Date())); sendSMSToAllNumbers(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
} else { } else {
String reply = MainApp.gs(R.string.smscommunicator_tempbasalcancelfailed); String reply = MainApp.gs(R.string.smscommunicator_tempbasalcancelfailed);
reply += "\n" + ConfigBuilderPlugin.getActivePump().shortStatus(true); reply += "\n" + ConfigBuilderPlugin.getActivePump().shortStatus(true);
sendSMS(new Sms(receivedSms.phoneNumber, reply, new Date())); sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
} }
} }
}); });
} else if (calibrationWaitingForConfirmation != null && !calibrationWaitingForConfirmation.processed && } else if (calibrationWaitingForConfirmation != null && !calibrationWaitingForConfirmation.processed &&
calibrationWaitingForConfirmation.confirmCode.equals(splited[0]) && System.currentTimeMillis() - calibrationWaitingForConfirmation.date.getTime() < Constants.SMS_CONFIRM_TIMEOUT) { calibrationWaitingForConfirmation.confirmCode.equals(splited[0]) && System.currentTimeMillis() - calibrationWaitingForConfirmation.date < Constants.SMS_CONFIRM_TIMEOUT) {
calibrationWaitingForConfirmation.processed = true; calibrationWaitingForConfirmation.processed = true;
boolean result = XdripCalibrations.sendIntent(calibrationWaitingForConfirmation.calibrationRequested); boolean result = XdripCalibrations.sendIntent(calibrationWaitingForConfirmation.calibrationRequested);
if (result) { if (result) {
reply = MainApp.gs(R.string.smscommunicator_calibrationsent); reply = MainApp.gs(R.string.smscommunicator_calibrationsent);
sendSMSToAllNumbers(new Sms(receivedSms.phoneNumber, reply, new Date())); sendSMSToAllNumbers(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
} else { } else {
reply = MainApp.gs(R.string.smscommunicator_calibrationfailed); reply = MainApp.gs(R.string.smscommunicator_calibrationfailed);
sendSMS(new Sms(receivedSms.phoneNumber, reply, new Date())); sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
} }
} else if (suspendWaitingForConfirmation != null && !suspendWaitingForConfirmation.processed && } else if (suspendWaitingForConfirmation != null && !suspendWaitingForConfirmation.processed &&
suspendWaitingForConfirmation.confirmCode.equals(splited[0]) && System.currentTimeMillis() - suspendWaitingForConfirmation.date.getTime() < Constants.SMS_CONFIRM_TIMEOUT) { suspendWaitingForConfirmation.confirmCode.equals(splited[0]) && System.currentTimeMillis() - suspendWaitingForConfirmation.date < Constants.SMS_CONFIRM_TIMEOUT) {
suspendWaitingForConfirmation.processed = true; suspendWaitingForConfirmation.processed = true;
ConfigBuilderPlugin.getCommandQueue().cancelTempBasal(true, new Callback() { ConfigBuilderPlugin.getCommandQueue().cancelTempBasal(true, new Callback() {
@Override @Override
@ -528,16 +528,16 @@ public class SmsCommunicatorPlugin extends PluginBase {
MainApp.bus().post(new EventRefreshOverview("SMS_LOOP_SUSPENDED")); MainApp.bus().post(new EventRefreshOverview("SMS_LOOP_SUSPENDED"));
String reply = MainApp.gs(R.string.smscommunicator_loopsuspended) + " " + String reply = MainApp.gs(R.string.smscommunicator_loopsuspended) + " " +
MainApp.gs(result.success ? R.string.smscommunicator_tempbasalcanceled : R.string.smscommunicator_tempbasalcancelfailed); MainApp.gs(result.success ? R.string.smscommunicator_tempbasalcanceled : R.string.smscommunicator_tempbasalcancelfailed);
sendSMSToAllNumbers(new Sms(receivedSms.phoneNumber, reply, new Date())); sendSMSToAllNumbers(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
} else { } else {
String reply = MainApp.gs(R.string.smscommunicator_tempbasalcancelfailed); String reply = MainApp.gs(R.string.smscommunicator_tempbasalcancelfailed);
reply += "\n" + ConfigBuilderPlugin.getActivePump().shortStatus(true); reply += "\n" + ConfigBuilderPlugin.getActivePump().shortStatus(true);
sendSMS(new Sms(receivedSms.phoneNumber, reply, new Date())); sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
} }
} }
}); });
} else { } else {
sendSMS(new Sms(receivedSms.phoneNumber, MainApp.gs(R.string.smscommunicator_unknowncommand), new Date())); sendSMS(new Sms(receivedSms.phoneNumber, MainApp.gs(R.string.smscommunicator_unknowncommand), System.currentTimeMillis()));
} }
resetWaitingMessages(); resetWaitingMessages();
break; break;
@ -549,7 +549,7 @@ public class SmsCommunicatorPlugin extends PluginBase {
public void sendNotificationToAllNumbers(String text) { public void sendNotificationToAllNumbers(String text) {
for (int i = 0; i < allowedNumbers.size(); i++) { for (int i = 0; i < allowedNumbers.size(); i++) {
Sms sms = new Sms(allowedNumbers.get(i), text, new Date()); Sms sms = new Sms(allowedNumbers.get(i), text, System.currentTimeMillis());
sendSMS(sms); sendSMS(sms);
} }
} }

View file

@ -4,6 +4,7 @@ import android.app.Activity;
import android.content.DialogInterface; import android.content.DialogInterface;
import android.graphics.Paint; import android.graphics.Paint;
import android.os.Bundle; import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog; import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView; import android.support.v7.widget.RecyclerView;
@ -19,28 +20,27 @@ import org.slf4j.LoggerFactory;
import java.util.List; import java.util.List;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.db.BgReading; import info.nightscout.androidaps.db.BgReading;
import info.nightscout.androidaps.events.EventNewBG; import info.nightscout.androidaps.events.EventNewBG;
import info.nightscout.androidaps.plugins.Common.SubscriberFragment; import info.nightscout.androidaps.plugins.Common.SubscriberFragment;
import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload;
import info.nightscout.utils.DateUtil; import info.nightscout.utils.DateUtil;
import info.nightscout.utils.FabricPrivacy; import info.nightscout.utils.FabricPrivacy;
import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload; import info.nightscout.utils.T;
/** /**
* Created by mike on 16.10.2017. * Created by mike on 16.10.2017.
*/ */
public class BGSourceFragment extends SubscriberFragment { public class BGSourceFragment extends SubscriberFragment {
private static Logger log = LoggerFactory.getLogger(BGSourceFragment.class);
RecyclerView recyclerView; RecyclerView recyclerView;
Profile profile; String units = Constants.MGDL;
final long MILLS_TO_THE_PAST = 12 * 60 * 60 * 1000L; final long MILLS_TO_THE_PAST = T.hours(12).msecs();
@Override @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, public View onCreateView(LayoutInflater inflater, ViewGroup container,
@ -57,7 +57,8 @@ public class BGSourceFragment extends SubscriberFragment {
RecyclerViewAdapter adapter = new RecyclerViewAdapter(MainApp.getDbHelper().getAllBgreadingsDataFromTime(now - MILLS_TO_THE_PAST, false)); RecyclerViewAdapter adapter = new RecyclerViewAdapter(MainApp.getDbHelper().getAllBgreadingsDataFromTime(now - MILLS_TO_THE_PAST, false));
recyclerView.setAdapter(adapter); recyclerView.setAdapter(adapter);
profile = MainApp.getConfigBuilder().getActiveProfileInterface().getProfile().getDefaultProfile(); if (MainApp.getConfigBuilder().getActiveProfileInterface() != null && MainApp.getConfigBuilder().getActiveProfileInterface().getProfile() != null && MainApp.getConfigBuilder().getActiveProfileInterface().getProfile().getDefaultProfile() != null)
units = MainApp.getConfigBuilder().getActiveProfileInterface().getProfile().getDefaultProfile().getUnits();
return view; return view;
} catch (Exception e) { } catch (Exception e) {
@ -68,8 +69,7 @@ public class BGSourceFragment extends SubscriberFragment {
} }
@Subscribe @Subscribe
@SuppressWarnings("unused") public void onStatusEvent(final EventNewBG unused) {
public void onStatusEvent(final EventNewBG ev) {
updateGUI(); updateGUI();
} }
@ -77,12 +77,9 @@ public class BGSourceFragment extends SubscriberFragment {
protected void updateGUI() { protected void updateGUI() {
Activity activity = getActivity(); Activity activity = getActivity();
if (activity != null) if (activity != null)
activity.runOnUiThread(new Runnable() { activity.runOnUiThread(() -> {
@Override long now = System.currentTimeMillis();
public void run() { recyclerView.swapAdapter(new RecyclerViewAdapter(MainApp.getDbHelper().getAllBgreadingsDataFromTime(now - MILLS_TO_THE_PAST, false)), true);
long now = System.currentTimeMillis();
recyclerView.swapAdapter(new BGSourceFragment.RecyclerViewAdapter(MainApp.getDbHelper().getAllBgreadingsDataFromTime(now - MILLS_TO_THE_PAST, false)), true);
}
}); });
} }
@ -101,12 +98,12 @@ public class BGSourceFragment extends SubscriberFragment {
} }
@Override @Override
public void onBindViewHolder(BgReadingsViewHolder holder, int position) { public void onBindViewHolder(@NonNull BgReadingsViewHolder holder, int position) {
BgReading bgReading = bgReadings.get(position); BgReading bgReading = bgReadings.get(position);
holder.ns.setVisibility(NSUpload.isIdValid(bgReading._id) ? View.VISIBLE : View.GONE); holder.ns.setVisibility(NSUpload.isIdValid(bgReading._id) ? View.VISIBLE : View.GONE);
holder.invalid.setVisibility(!bgReading.isValid ? View.VISIBLE : View.GONE); holder.invalid.setVisibility(!bgReading.isValid ? View.VISIBLE : View.GONE);
holder.date.setText(DateUtil.dateAndTimeString(bgReading.date)); holder.date.setText(DateUtil.dateAndTimeString(bgReading.date));
holder.value.setText(bgReading.valueToUnitsToString(profile.getUnits())); holder.value.setText(bgReading.valueToUnitsToString(units));
holder.direction.setText(bgReading.directionToSymbol()); holder.direction.setText(bgReading.directionToSymbol());
holder.remove.setTag(bgReading); holder.remove.setTag(bgReading);
} }
@ -144,7 +141,7 @@ public class BGSourceFragment extends SubscriberFragment {
case R.id.bgsource_remove: case R.id.bgsource_remove:
AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle(MainApp.gs(R.string.confirmation)); builder.setTitle(MainApp.gs(R.string.confirmation));
builder.setMessage(MainApp.gs(R.string.removerecord) + "\n" + DateUtil.dateAndTimeString(bgReading.date) + "\n" + bgReading.valueToUnitsToString(profile.getUnits())); builder.setMessage(MainApp.gs(R.string.removerecord) + "\n" + DateUtil.dateAndTimeString(bgReading.date) + "\n" + bgReading.valueToUnitsToString(units));
builder.setPositiveButton(MainApp.gs(R.string.ok), new DialogInterface.OnClickListener() { builder.setPositiveButton(MainApp.gs(R.string.ok), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) { public void onClick(DialogInterface dialog, int id) {
/* final String _id = bgReading._id; /* final String _id = bgReading._id;

View file

@ -1,6 +1,7 @@
package info.nightscout.androidaps.plugins.Treatments; package info.nightscout.androidaps.plugins.Treatments;
import android.graphics.Color; import android.graphics.Color;
import android.support.annotation.Nullable;
import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable; import com.j256.ormlite.table.DatabaseTable;
@ -10,6 +11,7 @@ import org.json.JSONObject;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.Date;
import java.util.Objects; import java.util.Objects;
import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.Constants;
@ -58,6 +60,8 @@ public class Treatment implements DataPointWithLabelInterface {
public int insulinInterfaceID = InsulinInterface.OREF_RAPID_ACTING; // currently unused, will be used in the future public int insulinInterfaceID = InsulinInterface.OREF_RAPID_ACTING; // currently unused, will be used in the future
@DatabaseField @DatabaseField
public double dia = Constants.defaultDIA; // currently unused, will be used in the future public double dia = Constants.defaultDIA; // currently unused, will be used in the future
@DatabaseField
public String boluscalc;
public Treatment() { public Treatment() {
} }
@ -78,6 +82,7 @@ public class Treatment implements DataPointWithLabelInterface {
double carbs = treatment.carbs; double carbs = treatment.carbs;
if (json.has("boluscalc")) { if (json.has("boluscalc")) {
JSONObject boluscalc = json.getJSONObject("boluscalc"); JSONObject boluscalc = json.getJSONObject("boluscalc");
treatment.boluscalc = boluscalc.toString();
if (boluscalc.has("carbs")) { if (boluscalc.has("carbs")) {
carbs = Math.max(boluscalc.getDouble("carbs"), carbs); carbs = Math.max(boluscalc.getDouble("carbs"), carbs);
} }
@ -91,7 +96,7 @@ public class Treatment implements DataPointWithLabelInterface {
public String toString() { public String toString() {
return "Treatment{" + return "Treatment{" +
"date= " + date + "date= " + date +
", date= " + DateUtil.dateAndTimeString(date) + ", date= " + new Date(date).toLocaleString() +
", isValid= " + isValid + ", isValid= " + isValid +
", isSMB= " + isSMB + ", isSMB= " + isSMB +
", _id= " + _id + ", _id= " + _id +
@ -130,6 +135,15 @@ public class Treatment implements DataPointWithLabelInterface {
return true; return true;
} }
@Nullable
public JSONObject getBoluscalc() {
try {
if (boluscalc != null)
return new JSONObject(boluscalc);
} catch (JSONException ignored) {
}
return null;
}
/* /*
* mealBolus, _id and isSMB cannot be known coming from pump. Only compare rest * mealBolus, _id and isSMB cannot be known coming from pump. Only compare rest

View file

@ -122,6 +122,13 @@ public class TreatmentService extends OrmLiteBaseService<DatabaseHelper> {
log.error("Can't create database", e); log.error("Can't create database", e);
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} else if (oldVersion == 8 && newVersion == 9) {
log.debug("Upgrading database from v8 to v9");
try {
getDao().executeRaw("ALTER TABLE `" + Treatment.TABLE_TREATMENTS + "` ADD COLUMN boluscalc STRING;");
} catch (SQLException e) {
e.printStackTrace();
}
} else { } else {
if (L.isEnabled(L.DATATREATMENTS)) if (L.isEnabled(L.DATATREATMENTS))
log.info("onUpgrade"); log.info("onUpgrade");
@ -130,7 +137,13 @@ public class TreatmentService extends OrmLiteBaseService<DatabaseHelper> {
} }
public void onDowngrade(ConnectionSource connectionSource, int oldVersion, int newVersion) { public void onDowngrade(ConnectionSource connectionSource, int oldVersion, int newVersion) {
// this method is not supported right now if (oldVersion == 9 && newVersion == 8) {
try {
getDao().executeRaw("ALTER TABLE `" + Treatment.TABLE_TREATMENTS + "` DROP COLUMN boluscalc STRING;");
} catch (SQLException e) {
e.printStackTrace();
}
}
} }
public void resetTreatments() { public void resetTreatments() {

View file

@ -506,6 +506,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
treatment.carbs = detailedBolusInfo.carbs; treatment.carbs = detailedBolusInfo.carbs;
treatment.source = detailedBolusInfo.source; treatment.source = detailedBolusInfo.source;
treatment.mealBolus = treatment.carbs > 0; treatment.mealBolus = treatment.carbs > 0;
treatment.boluscalc = detailedBolusInfo.boluscalc != null ? detailedBolusInfo.boluscalc.toString() : null;
TreatmentService.UpdateReturn creatOrUpdateResult = getService().createOrUpdate(treatment); TreatmentService.UpdateReturn creatOrUpdateResult = getService().createOrUpdate(treatment);
boolean newRecordCreated = creatOrUpdateResult.newRecord; boolean newRecordCreated = creatOrUpdateResult.newRecord;
//log.debug("Adding new Treatment record" + treatment.toString()); //log.debug("Adding new Treatment record" + treatment.toString());

View file

@ -0,0 +1,88 @@
package info.nightscout.androidaps.plugins.Treatments.dialogs;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.TextView;
import org.json.JSONObject;
import info.nightscout.androidaps.R;
import info.nightscout.utils.DecimalFormatter;
import info.nightscout.utils.JsonHelper;
public class WizardInfoDialog extends DialogFragment implements OnClickListener {
JSONObject json;
public WizardInfoDialog() {
super();
}
public void setData(JSONObject json) {
this.json = json;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.treatments_wizardinfo_dialog, null, false);
getDialog().getWindow().requestFeature(Window.FEATURE_CUSTOM_TITLE);
getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
view.findViewById(R.id.ok).setOnClickListener(this);
// BG
((TextView) view.findViewById(R.id.treatments_wizard_bg)).setText(DecimalFormatter.to1Decimal(JsonHelper.safeGetDouble(json, "bg")) + " ISF: " + DecimalFormatter.to1Decimal(JsonHelper.safeGetDouble(json, "isf")));
((TextView) view.findViewById(R.id.treatments_wizard_bginsulin)).setText(DecimalFormatter.to2Decimal(JsonHelper.safeGetDouble(json, "insulinbg")) + "U");
((CheckBox) view.findViewById(R.id.treatments_wizard_bgcheckbox)).setChecked(JsonHelper.safeGetBoolean(json, "insulinbgused"));
((CheckBox) view.findViewById(R.id.treatments_wizard_ttcheckbox)).setChecked(JsonHelper.safeGetBoolean(json, "ttused"));
// Trend
((TextView) view.findViewById(R.id.treatments_wizard_bgtrend)).setText(JsonHelper.safeGetString(json, "trend"));
((TextView) view.findViewById(R.id.treatments_wizard_bgtrendinsulin)).setText(DecimalFormatter.to2Decimal(JsonHelper.safeGetDouble(json, "insulintrend")) + "U");
((CheckBox) view.findViewById(R.id.treatments_wizard_bgtrendcheckbox)).setChecked(JsonHelper.safeGetBoolean(json, "trendused"));
// COB
((TextView) view.findViewById(R.id.treatments_wizard_cob)).setText(DecimalFormatter.to0Decimal(JsonHelper.safeGetDouble(json, "cob")) + "g IC: " + DecimalFormatter.to1Decimal(JsonHelper.safeGetDouble(json, "ic")));
((TextView) view.findViewById(R.id.treatments_wizard_cobinsulin)).setText(DecimalFormatter.to2Decimal(JsonHelper.safeGetDouble(json, "insulincob")) + "U");
((CheckBox) view.findViewById(R.id.treatments_wizard_cobcheckbox)).setChecked(JsonHelper.safeGetBoolean(json, "cobused"));
// Bolus IOB
((TextView) view.findViewById(R.id.treatments_wizard_bolusiobinsulin)).setText(DecimalFormatter.to2Decimal(JsonHelper.safeGetDouble(json, "bolusiob")) + "U");
((CheckBox) view.findViewById(R.id.treatments_wizard_bolusiobcheckbox)).setChecked(JsonHelper.safeGetBoolean(json, "bolusiobused"));
// Basal IOB
((TextView) view.findViewById(R.id.treatments_wizard_basaliobinsulin)).setText(DecimalFormatter.to2Decimal(JsonHelper.safeGetDouble(json, "basaliob")) + "U");
((CheckBox) view.findViewById(R.id.treatments_wizard_basaliobcheckbox)).setChecked(JsonHelper.safeGetBoolean(json, "basaliobused"));
// Superbolus
((TextView) view.findViewById(R.id.treatments_wizard_sbinsulin)).setText(DecimalFormatter.to2Decimal(JsonHelper.safeGetDouble(json, "insulinsuperbolus")) + "U");
((CheckBox) view.findViewById(R.id.treatments_wizard_sbcheckbox)).setChecked(JsonHelper.safeGetBoolean(json, "superbolusused"));
// Carbs
((TextView) view.findViewById(R.id.treatments_wizard_carbs)).setText(DecimalFormatter.to0Decimal(JsonHelper.safeGetDouble(json, "carbs")) + "g IC: " + DecimalFormatter.to1Decimal(JsonHelper.safeGetDouble(json, "ic")));
((TextView) view.findViewById(R.id.treatments_wizard_carbsinsulin)).setText(DecimalFormatter.to2Decimal(JsonHelper.safeGetDouble(json, "insulincarbs")) + "U");
// Correction
((TextView) view.findViewById(R.id.treatments_wizard_correctioninsulin)).setText(DecimalFormatter.to2Decimal(JsonHelper.safeGetDouble(json, "othercorrection")) + "U");
// Profile
((TextView) view.findViewById(R.id.treatments_wizard_profile)).setText(JsonHelper.safeGetString(json, "profile"));
// Notes
((TextView) view.findViewById(R.id.treatments_wizard_notes)).setText(JsonHelper.safeGetString(json, "notes"));
// Total
((TextView) view.findViewById(R.id.treatments_wizard_totalinsulin)).setText(DecimalFormatter.to2Decimal(JsonHelper.safeGetDouble(json, "insulin")) + "U");
setCancelable(true);
return view;
}
@Override
public synchronized void onClick(View view) {
switch (view.getId()) {
case R.id.ok:
dismiss();
break;
}
}
}

View file

@ -6,6 +6,7 @@ import android.content.DialogInterface;
import android.content.Intent; import android.content.Intent;
import android.graphics.Paint; import android.graphics.Paint;
import android.os.Bundle; import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.content.ContextCompat; import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog; import android.support.v7.app.AlertDialog;
import android.support.v7.widget.CardView; import android.support.v7.widget.CardView;
@ -20,25 +21,28 @@ import android.widget.TextView;
import com.crashlytics.android.answers.CustomEvent; import com.crashlytics.android.answers.CustomEvent;
import com.squareup.otto.Subscribe; import com.squareup.otto.Subscribe;
import org.json.JSONObject;
import java.util.List; import java.util.List;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions;
import info.nightscout.androidaps.services.Intents;
import info.nightscout.androidaps.data.Iob; import info.nightscout.androidaps.data.Iob;
import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.db.Source; import info.nightscout.androidaps.db.Source;
import info.nightscout.androidaps.plugins.Treatments.Treatment;
import info.nightscout.androidaps.events.EventNewBG; import info.nightscout.androidaps.events.EventNewBG;
import info.nightscout.androidaps.events.EventTreatmentChange; import info.nightscout.androidaps.events.EventTreatmentChange;
import info.nightscout.androidaps.plugins.Common.SubscriberFragment; import info.nightscout.androidaps.plugins.Common.SubscriberFragment;
import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload;
import info.nightscout.androidaps.plugins.NSClientInternal.UploadQueue; import info.nightscout.androidaps.plugins.NSClientInternal.UploadQueue;
import info.nightscout.androidaps.plugins.Treatments.Treatment;
import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin; import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin;
import info.nightscout.utils.FabricPrivacy; import info.nightscout.androidaps.plugins.Treatments.dialogs.WizardInfoDialog;
import info.nightscout.androidaps.services.Intents;
import info.nightscout.utils.DateUtil; import info.nightscout.utils.DateUtil;
import info.nightscout.utils.DecimalFormatter; import info.nightscout.utils.DecimalFormatter;
import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload; import info.nightscout.utils.FabricPrivacy;
import info.nightscout.utils.SP; import info.nightscout.utils.SP;
import static info.nightscout.utils.DateUtil.now; import static info.nightscout.utils.DateUtil.now;
@ -79,7 +83,6 @@ public class TreatmentsBolusFragment extends SubscriberFragment implements View.
holder.carbs.setText(DecimalFormatter.to0Decimal(t.carbs) + " g"); holder.carbs.setText(DecimalFormatter.to0Decimal(t.carbs) + " g");
Iob iob = t.iobCalc(System.currentTimeMillis(), profile.getDia()); Iob iob = t.iobCalc(System.currentTimeMillis(), profile.getDia());
holder.iob.setText(DecimalFormatter.to2Decimal(iob.iobContrib) + " U"); holder.iob.setText(DecimalFormatter.to2Decimal(iob.iobContrib) + " U");
holder.activity.setText(DecimalFormatter.to3Decimal(iob.activityContrib) + " U");
holder.mealOrCorrection.setText(t.isSMB ? "SMB" : t.mealBolus ? MainApp.gs(R.string.mealbolus) : MainApp.gs(R.string.correctionbous)); holder.mealOrCorrection.setText(t.isSMB ? "SMB" : t.mealBolus ? MainApp.gs(R.string.mealbolus) : MainApp.gs(R.string.correctionbous));
holder.ph.setVisibility(t.source == Source.PUMP ? View.VISIBLE : View.GONE); holder.ph.setVisibility(t.source == Source.PUMP ? View.VISIBLE : View.GONE);
holder.ns.setVisibility(NSUpload.isIdValid(t._id) ? View.VISIBLE : View.GONE); holder.ns.setVisibility(NSUpload.isIdValid(t._id) ? View.VISIBLE : View.GONE);
@ -93,6 +96,8 @@ public class TreatmentsBolusFragment extends SubscriberFragment implements View.
else else
holder.date.setTextColor(holder.carbs.getCurrentTextColor()); holder.date.setTextColor(holder.carbs.getCurrentTextColor());
holder.remove.setTag(t); holder.remove.setTag(t);
holder.calculation.setTag(t);
holder.calculation.setVisibility(t.getBoluscalc() == null ? View.INVISIBLE : View.VISIBLE);
} }
@Override @Override
@ -111,9 +116,9 @@ public class TreatmentsBolusFragment extends SubscriberFragment implements View.
TextView insulin; TextView insulin;
TextView carbs; TextView carbs;
TextView iob; TextView iob;
TextView activity;
TextView mealOrCorrection; TextView mealOrCorrection;
TextView remove; TextView remove;
TextView calculation;
TextView ph; TextView ph;
TextView ns; TextView ns;
TextView invalid; TextView invalid;
@ -125,11 +130,13 @@ public class TreatmentsBolusFragment extends SubscriberFragment implements View.
insulin = (TextView) itemView.findViewById(R.id.treatments_insulin); insulin = (TextView) itemView.findViewById(R.id.treatments_insulin);
carbs = (TextView) itemView.findViewById(R.id.treatments_carbs); carbs = (TextView) itemView.findViewById(R.id.treatments_carbs);
iob = (TextView) itemView.findViewById(R.id.treatments_iob); iob = (TextView) itemView.findViewById(R.id.treatments_iob);
activity = (TextView) itemView.findViewById(R.id.treatments_activity);
mealOrCorrection = (TextView) itemView.findViewById(R.id.treatments_mealorcorrection); mealOrCorrection = (TextView) itemView.findViewById(R.id.treatments_mealorcorrection);
ph = (TextView) itemView.findViewById(R.id.pump_sign); ph = (TextView) itemView.findViewById(R.id.pump_sign);
ns = (TextView) itemView.findViewById(R.id.ns_sign); ns = (TextView) itemView.findViewById(R.id.ns_sign);
invalid = (TextView) itemView.findViewById(R.id.invalid_sign); invalid = (TextView) itemView.findViewById(R.id.invalid_sign);
calculation = (TextView) itemView.findViewById(R.id.treatments_calculation);
calculation.setOnClickListener(this);
calculation.setPaintFlags(calculation.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
remove = (TextView) itemView.findViewById(R.id.treatments_remove); remove = (TextView) itemView.findViewById(R.id.treatments_remove);
remove.setOnClickListener(this); remove.setOnClickListener(this);
remove.setPaintFlags(remove.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG); remove.setPaintFlags(remove.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
@ -164,6 +171,18 @@ public class TreatmentsBolusFragment extends SubscriberFragment implements View.
builder.setNegativeButton(MainApp.gs(R.string.cancel), null); builder.setNegativeButton(MainApp.gs(R.string.cancel), null);
builder.show(); builder.show();
break; break;
case R.id.treatments_calculation:
FragmentManager manager = getFragmentManager();
// try to fix https://fabric.io/nightscout3/android/apps/info.nightscout.androidaps/issues/5aca7a1536c7b23527eb4be7?time=last-seven-days
// https://stackoverflow.com/questions/14860239/checking-if-state-is-saved-before-committing-a-fragmenttransaction
if (manager.isStateSaved())
return;
if (treatment.getBoluscalc() != null) {
WizardInfoDialog wizardDialog = new WizardInfoDialog();
wizardDialog.setData(treatment.getBoluscalc());
wizardDialog.show(manager, "WizardInfoDialog");
}
break;
} }
} }
} }

View file

@ -167,7 +167,9 @@ public class CommandQueue {
} }
} }
public static void independentConnect(String reason, Callback callback) { public void independentConnect(String reason, Callback callback) {
if (L.isEnabled(L.PUMPQUEUE))
log.debug("Starting new queue");
CommandQueue tempCommandQueue = new CommandQueue(); CommandQueue tempCommandQueue = new CommandQueue();
tempCommandQueue.readStatus(reason, callback); tempCommandQueue.readStatus(reason, callback);
} }

View file

@ -101,6 +101,14 @@ public class QueueThread extends Thread {
} }
} }
if (pump.isHandshakeInProgress()) {
if (L.isEnabled(L.PUMPQUEUE))
log.debug("handshaking " + secondsElapsed);
MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.HANDSHAKING, (int) secondsElapsed));
SystemClock.sleep(100);
continue;
}
if (pump.isConnecting()) { if (pump.isConnecting()) {
if (L.isEnabled(L.PUMPQUEUE)) if (L.isEnabled(L.PUMPQUEUE))
log.debug("connecting " + secondsElapsed); log.debug("connecting " + secondsElapsed);
@ -109,7 +117,6 @@ public class QueueThread extends Thread {
continue; continue;
} }
if (!pump.isConnected()) { if (!pump.isConnected()) {
if (L.isEnabled(L.PUMPQUEUE)) if (L.isEnabled(L.PUMPQUEUE))
log.debug("connect"); log.debug("connect");
@ -161,6 +168,8 @@ public class QueueThread extends Thread {
} }
} finally { } finally {
mWakeLock.release(); mWakeLock.release();
if (L.isEnabled(L.PUMPQUEUE))
log.debug("thread end");
} }
} }
} }

View file

@ -3,10 +3,13 @@ package info.nightscout.androidaps.queue.commands;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.data.PumpEnactResult;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.queue.Callback; import info.nightscout.androidaps.queue.Callback;
import info.nightscout.utils.LocalAlertUtils; import info.nightscout.utils.LocalAlertUtils;
import info.nightscout.utils.T;
/** /**
* Created by mike on 09.11.2017. * Created by mike on 09.11.2017.
@ -29,8 +32,15 @@ public class CommandReadStatus extends Command {
LocalAlertUtils.notifyPumpStatusRead(); LocalAlertUtils.notifyPumpStatusRead();
if (L.isEnabled(L.PUMPQUEUE)) if (L.isEnabled(L.PUMPQUEUE))
log.debug("CommandReadStatus executed. Reason: " + reason); log.debug("CommandReadStatus executed. Reason: " + reason);
final PumpInterface pump = ConfigBuilderPlugin.getActivePump();
PumpEnactResult result = new PumpEnactResult().success(false);
if (pump != null) {
long lastConnection = pump.lastDataTime();
if (lastConnection > System.currentTimeMillis() - T.mins(1).msecs())
result.success(true);
}
if (callback != null) if (callback != null)
callback.result(null).run(); callback.result(result).run();
} }
@Override @Override

View file

@ -7,11 +7,11 @@ import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.os.PowerManager; import android.os.PowerManager;
import com.crashlytics.android.answers.CustomEvent;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.Date;
import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.Profile;
@ -24,6 +24,7 @@ import info.nightscout.androidaps.queue.commands.Command;
import info.nightscout.utils.DateUtil; import info.nightscout.utils.DateUtil;
import info.nightscout.utils.FabricPrivacy; import info.nightscout.utils.FabricPrivacy;
import info.nightscout.utils.LocalAlertUtils; import info.nightscout.utils.LocalAlertUtils;
import info.nightscout.utils.T;
/** /**
@ -31,7 +32,9 @@ import info.nightscout.utils.LocalAlertUtils;
*/ */
public class KeepAliveReceiver extends BroadcastReceiver { public class KeepAliveReceiver extends BroadcastReceiver {
private static Logger log = LoggerFactory.getLogger(L.CORE); private static Logger log = LoggerFactory.getLogger(L.CORE);
public static final long STATUS_UPDATE_FREQUENCY = 15 * 60 * 1000L; public static final long STATUS_UPDATE_FREQUENCY = T.mins(15).msecs();
private static long lastReadStatus = 0;
private static long lastRun = 0;
public static void cancelAlarm(Context context) { public static void cancelAlarm(Context context) {
Intent intent = new Intent(context, KeepAliveReceiver.class); Intent intent = new Intent(context, KeepAliveReceiver.class);
@ -60,22 +63,33 @@ public class KeepAliveReceiver extends BroadcastReceiver {
final PumpInterface pump = ConfigBuilderPlugin.getActivePump(); final PumpInterface pump = ConfigBuilderPlugin.getActivePump();
final Profile profile = ProfileFunctions.getInstance().getProfile(); final Profile profile = ProfileFunctions.getInstance().getProfile();
if (pump != null && profile != null) { if (pump != null && profile != null) {
Date lastConnection = pump.lastDataTime(); long lastConnection = pump.lastDataTime();
boolean isStatusOutdated = lastConnection.getTime() + STATUS_UPDATE_FREQUENCY < System.currentTimeMillis(); boolean isStatusOutdated = lastConnection + STATUS_UPDATE_FREQUENCY < System.currentTimeMillis();
boolean isBasalOutdated = Math.abs(profile.getBasal() - pump.getBaseBasalRate()) > pump.getPumpDescription().basalStep; boolean isBasalOutdated = Math.abs(profile.getBasal() - pump.getBaseBasalRate()) > pump.getPumpDescription().basalStep;
if (L.isEnabled(L.CORE)) if (L.isEnabled(L.CORE))
log.debug("Last connection: " + DateUtil.dateAndTimeString(lastConnection)); log.debug("Last connection: " + DateUtil.dateAndTimeString(lastConnection));
LocalAlertUtils.checkPumpUnreachableAlarm(lastConnection, isStatusOutdated); // sometimes keepalive broadcast stops
// as as workaround test if readStatus was requested before an alarm is generated
if (lastReadStatus != 0 && lastReadStatus > System.currentTimeMillis() - T.mins(5).msecs()) {
LocalAlertUtils.checkPumpUnreachableAlarm(lastConnection, isStatusOutdated);
}
if (!pump.isThisProfileSet(profile) && !ConfigBuilderPlugin.getCommandQueue().isRunning(Command.CommandType.BASALPROFILE)) { if (!pump.isThisProfileSet(profile) && !ConfigBuilderPlugin.getCommandQueue().isRunning(Command.CommandType.BASALPROFILE)) {
MainApp.bus().post(new EventProfileSwitchChange()); MainApp.bus().post(new EventProfileSwitchChange());
} else if (isStatusOutdated && !pump.isBusy()) { } else if (isStatusOutdated && !pump.isBusy()) {
lastReadStatus = System.currentTimeMillis();
ConfigBuilderPlugin.getCommandQueue().readStatus("KeepAlive. Status outdated.", null); ConfigBuilderPlugin.getCommandQueue().readStatus("KeepAlive. Status outdated.", null);
} else if (isBasalOutdated && !pump.isBusy()) { } else if (isBasalOutdated && !pump.isBusy()) {
lastReadStatus = System.currentTimeMillis();
ConfigBuilderPlugin.getCommandQueue().readStatus("KeepAlive. Basal outdated.", null); ConfigBuilderPlugin.getCommandQueue().readStatus("KeepAlive. Basal outdated.", null);
} }
} }
if (lastRun != 0 && System.currentTimeMillis() - lastRun > T.mins(10).msecs()) {
log.error("KeepAlive fail");
FabricPrivacy.getInstance().logCustom(new CustomEvent("KeepAliveFail"));
}
lastRun = System.currentTimeMillis();
} }
//called by MainApp at first app start //called by MainApp at first app start

View file

@ -97,27 +97,27 @@ public class DateUtil {
} }
public static String dateString(Date date) { public static String dateString(Date date) {
//return DateUtils.formatDateTime(MainApp.instance(), date.getTime(), DateUtils.FORMAT_SHOW_DATE); this provide month name not number
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT); DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
return df.format(date); return df.format(date);
} }
public static String dateString(long mills) { public static String dateString(long mills) {
//return DateUtils.formatDateTime(MainApp.instance(), mills, DateUtils.FORMAT_SHOW_DATE); this provide month name not number
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT); DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
return df.format(mills); return df.format(mills);
} }
public static String timeString(Date date) { public static String timeString(Date date) {
//return DateUtils.formatDateTime(MainApp.instance(), date.getTime(), DateUtils.FORMAT_SHOW_TIME);
return new DateTime(date).toString(DateTimeFormat.shortTime()); return new DateTime(date).toString(DateTimeFormat.shortTime());
} }
public static String timeString(long mills) { public static String timeString(long mills) {
//return DateUtils.formatDateTime(MainApp.instance(), mills, DateUtils.FORMAT_SHOW_TIME);
return new DateTime(mills).toString(DateTimeFormat.shortTime()); return new DateTime(mills).toString(DateTimeFormat.shortTime());
} }
public static String timeFullString(long mills) {
return new DateTime(mills).toString(DateTimeFormat.fullTime());
}
public static String dateAndTimeString(Date date) { public static String dateAndTimeString(Date date) {
return dateString(date) + " " + timeString(date); return dateString(date) + " " + timeString(date);
} }
@ -130,6 +130,10 @@ public class DateUtil {
return dateString(mills) + " " + timeString(mills); return dateString(mills) + " " + timeString(mills);
} }
public static String dateAndTimeFullString(long mills) {
return dateString(mills) + " " + timeFullString(mills);
}
public static String minAgo(long time) { public static String minAgo(long time) {
int mins = (int) ((now() - time) / 1000 / 60); int mins = (int) ((now() - time) / 1000 / 60);
return MainApp.gs(R.string.minago, mins); return MainApp.gs(R.string.minago, mins);

View file

@ -3,6 +3,7 @@ package info.nightscout.utils;
import com.crashlytics.android.Crashlytics; import com.crashlytics.android.Crashlytics;
import com.crashlytics.android.answers.Answers; import com.crashlytics.android.answers.Answers;
import com.crashlytics.android.answers.CustomEvent; import com.crashlytics.android.answers.CustomEvent;
import info.nightscout.androidaps.BuildConfig; import info.nightscout.androidaps.BuildConfig;
import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
@ -13,11 +14,10 @@ import java.util.Date;
/** /**
* Created by jamorham on 21/02/2018. * Created by jamorham on 21/02/2018.
* * <p>
* Some users do not wish to be tracked, Fabric Answers and Crashlytics do not provide an easy way * Some users do not wish to be tracked, Fabric Answers and Crashlytics do not provide an easy way
* to disable them and make calls from a potentially invalid singleton reference. This wrapper * to disable them and make calls from a potentially invalid singleton reference. This wrapper
* emulates the methods but ignores the request if the instance is null or invalid. * emulates the methods but ignores the request if the instance is null or invalid.
*
*/ */
public class FabricPrivacy { public class FabricPrivacy {
@ -110,8 +110,11 @@ public class FabricPrivacy {
CustomEvent pluginStats = new CustomEvent("PluginStats"); CustomEvent pluginStats = new CustomEvent("PluginStats");
pluginStats.putCustomAttribute("version", BuildConfig.VERSION); pluginStats.putCustomAttribute("version", BuildConfig.VERSION);
for (PluginBase plugin : MainApp.getPluginsList()) { for (PluginBase plugin : MainApp.getPluginsList()) {
if (plugin.isEnabled(plugin.getType()) && !plugin.pluginDescription.alwaysEnabled) { if (!plugin.pluginDescription.alwaysEnabled) {
pluginStats.putCustomAttribute(plugin.getClass().getSimpleName(), "enabled"); if (plugin.isEnabled(plugin.getType()))
pluginStats.putCustomAttribute(plugin.getClass().getSimpleName(), "enabled");
else
pluginStats.putCustomAttribute(plugin.getClass().getSimpleName(), "disabled");
} }
} }

View file

@ -3,8 +3,6 @@ package info.nightscout.utils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.Date;
import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
@ -35,8 +33,8 @@ public class LocalAlertUtils {
return T.mins(SP.getInt(MainApp.gs(R.string.key_pump_unreachable_threshold), 30)).msecs(); return T.mins(SP.getInt(MainApp.gs(R.string.key_pump_unreachable_threshold), 30)).msecs();
} }
public static void checkPumpUnreachableAlarm(Date lastConnection, boolean isStatusOutdated) { public static void checkPumpUnreachableAlarm(long lastConnection, boolean isStatusOutdated) {
boolean alarmTimeoutExpired = lastConnection.getTime() + pumpUnreachableThreshold() < System.currentTimeMillis(); boolean alarmTimeoutExpired = lastConnection + pumpUnreachableThreshold() < System.currentTimeMillis();
boolean nextAlarmOccurrenceReached = SP.getLong("nextPumpDisconnectedAlarm", 0L) < System.currentTimeMillis(); boolean nextAlarmOccurrenceReached = SP.getLong("nextPumpDisconnectedAlarm", 0L) < System.currentTimeMillis();
if (Config.APS && SP.getBoolean(MainApp.gs(R.string.key_enable_pump_unreachable_alert), true) if (Config.APS && SP.getBoolean(MainApp.gs(R.string.key_enable_pump_unreachable_alert), true)
@ -83,8 +81,8 @@ public class LocalAlertUtils {
final PumpInterface pump = ConfigBuilderPlugin.getActivePump(); final PumpInterface pump = ConfigBuilderPlugin.getActivePump();
final Profile profile = ProfileFunctions.getInstance().getProfile(); final Profile profile = ProfileFunctions.getInstance().getProfile();
if (pump != null && profile != null) { if (pump != null && profile != null) {
Date lastConnection = pump.lastDataTime(); long lastConnection = pump.lastDataTime();
long earliestAlarmTime = lastConnection.getTime() + pumpUnreachableThreshold(); long earliestAlarmTime = lastConnection + pumpUnreachableThreshold();
if (SP.getLong("nextPumpDisconnectedAlarm", 0l) < earliestAlarmTime) { if (SP.getLong("nextPumpDisconnectedAlarm", 0l) < earliestAlarmTime) {
SP.putLong("nextPumpDisconnectedAlarm", earliestAlarmTime); SP.putLong("nextPumpDisconnectedAlarm", earliestAlarmTime);
} }

View file

@ -2,8 +2,6 @@ package info.nightscout.utils;
import org.slf4j.Logger; import org.slf4j.Logger;
import java.util.Date;
/** /**
* Created by mike on 29.01.2017. * Created by mike on 29.01.2017.
*/ */
@ -11,8 +9,8 @@ import java.util.Date;
public class Profiler { public class Profiler {
public Profiler(){} public Profiler(){}
static public void log(Logger log, String function, Date start) { static public void log(Logger log, String function, long start) {
long msec = System.currentTimeMillis() - start.getTime(); long msec = System.currentTimeMillis() - start;
log.debug(">>> " + function + " <<< executed in " + msec + " miliseconds"); log.debug(">>> " + function + " <<< executed in " + msec + " miliseconds");
} }
} }

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