- started working TBR

- added Dropbox stuff (not part of project)
This commit is contained in:
Andy Rozman 2021-05-05 16:57:48 +01:00
parent 1e88a1a1ed
commit 12a3609565
6 changed files with 378 additions and 62 deletions

View file

@ -0,0 +1,72 @@
package info.nightscout.androidaps.plugins.general.maintenance.dropbox;
import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;
import com.dropbox.core.DbxException;
import com.dropbox.core.v2.DbxClientV2;
import com.dropbox.core.v2.files.FileMetadata;
import com.dropbox.core.v2.files.WriteMode;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
public class UploadFileTask extends AsyncTask<String, Void, FileMetadata> {
private final Context mContext;
private final DbxClientV2 mDbxClient;
private final Callback mCallback;
private Exception mException;
public interface Callback {
void onUploadComplete(FileMetadata result);
void onError(Exception e);
}
UploadFileTask(Context context, DbxClientV2 dbxClient, Callback callback) {
mContext = context;
mDbxClient = dbxClient;
mCallback = callback;
}
@Override
protected void onPostExecute(FileMetadata result) {
super.onPostExecute(result);
if (mException != null) {
mCallback.onError(mException);
} else if (result == null) {
mCallback.onError(null);
} else {
mCallback.onUploadComplete(result);
}
}
@Override
protected FileMetadata doInBackground(String... params) {
String localUri = params[0];
File localFile = UriHelpers.getFileForUri(mContext, Uri.parse(localUri));
if (localFile != null) {
String remoteFolderPath = params[1];
// Note - this is not ensuring the name is a valid dropbox file name
String remoteFileName = localFile.getName();
try (InputStream inputStream = new FileInputStream(localFile)) {
return mDbxClient.files().uploadBuilder(remoteFolderPath + "/" + remoteFileName)
.withMode(WriteMode.OVERWRITE)
.uploadAndFinish(inputStream);
} catch (DbxException | IOException e) {
mException = e;
}
}
return null;
}
}

View file

@ -0,0 +1,119 @@
package info.nightscout.androidaps.plugins.general.maintenance.dropbox;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import java.io.File;
public class UriHelpers {
private UriHelpers() {}
/**
* Get the file path for a uri. This is a convoluted way to get the path for an Uri created using the
* StorageAccessFramework. This in no way is the official way to do this but there does not seem to be a better
* way to do this at this point. It is taken from https://github.com/iPaulPro/aFileChooser.
*
* @param context The context of the application
* @param uri The uri of the saved file
* @return The file with path pointing to the saved file. It can return null if we can't resolve the uri properly.
*/
public static File getFileForUri(final Context context, final Uri uri) {
String path = null;
// DocumentProvider
if (DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
path = Environment.getExternalStorageDirectory() + "/" + split[1];
}
} else if (isDownloadsDocument(uri)) {
// DownloadsProvider
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris
.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
path = getDataColumn(context, contentUri, null, null);
} else if (isMediaDocument(uri)) {
// MediaProvider
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[] {
split[1]
};
path = getDataColumn(context, contentUri, selection, selectionArgs);
}
} else if ("content".equalsIgnoreCase(uri.getScheme())) {
// MediaStore (and general)
path = getDataColumn(context, uri, null, null);
} else if ("file".equalsIgnoreCase(uri.getScheme())) {
// File
path = uri.getPath();
}
if (path != null) {
return new File(path);
}
return null;
}
private static String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {
column
};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
null);
if (cursor != null && cursor.moveToFirst()) {
final int column_index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(column_index);
}
} finally {
if (cursor != null) {
cursor.close();
}
}
return null;
}
private static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
private static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
private static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
}

View file

@ -8,6 +8,7 @@ import info.nightscout.androidaps.db.TemporaryBasal
import info.nightscout.androidaps.interfaces.PumpSync
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.pump.common.defs.PumpType
import info.nightscout.androidaps.utils.sharedPreferences.SP
import java.lang.reflect.Type
import java.util.*
@ -132,12 +133,17 @@ class PumpSyncStorage @Inject constructor(
// TODO
fun addTemporaryBasalRateWithTempId(temporaryBasal: PumpDbEntryTBR, writeToInternalHistory: Boolean, creator: PumpSyncEntriesCreator) : Boolean {
val timenow : Long = System.currentTimeMillis()
val temporaryId = creator.generateTempId(timenow)
val response = false
// pumpSync.addBolusWithTempId(temporaryBasal.timestamp, detailedBolusInfo.insulin,
// generateTempId(detailedBolusInfo.timestamp), detailedBolusInfo.getBolusType(),
// getPumpType(), serialNumber());
val response = pumpSync.addTemporaryBasalWithTempId(
timenow,
temporaryBasal.rate,
(temporaryBasal.durationInMinutes * 60L * 1000L),
temporaryBasal.isAbsolute,
temporaryId,
temporaryBasal.tbrType,
creator.model(),
creator.serialNumber())
if (response && writeToInternalHistory) {
var innerList: MutableList<PumpDbEntry> = pumpSyncStorage[TBR]!!

View file

@ -759,17 +759,17 @@ class MedtronicPumpPlugin @Inject constructor(
medtronicPumpStatus.tempBasalStart = Date()
medtronicPumpStatus.tempBasalAmount = absoluteRate
medtronicPumpStatus.tempBasalLength = durationInMinutes
val tempStart = TemporaryBasal(injector) //
.date(System.currentTimeMillis()) //
.duration(durationInMinutes) //
.absolute(absoluteRate) //
.source(Source.USER)
activePlugin.activeTreatments.addToHistoryTempBasal(tempStart)
// val tempData = PumpDbEntryTBR(absoluteRate, true, durationInMinutes, tbrType)
// val tempStart = TemporaryBasal(injector) //
// .date(System.currentTimeMillis()) //
// .duration(durationInMinutes) //
// .absolute(absoluteRate) //
// .source(Source.USER)
//
// pumpSyncStorage.addTemporaryBasalRateWithTempId(tempData, true, this)
// activePlugin.activeTreatments.addToHistoryTempBasal(tempStart)
val tempData = PumpDbEntryTBR(absoluteRate, true, durationInMinutes, tbrType)
pumpSyncStorage.addTemporaryBasalRateWithTempId(tempData, true, this)
incrementStatistics(MedtronicConst.Statistics.TBRsSet)
finishAction("TBR")
@ -1003,17 +1003,17 @@ class MedtronicPumpPlugin @Inject constructor(
finishAction("TBR")
return if (response!!) {
aapsLogger.info(LTag.PUMP, logPrefix + "cancelTempBasal - Cancel TBR successful.")
val tempBasal = TemporaryBasal(injector) //
.date(System.currentTimeMillis()) //
.duration(0) //
.source(Source.USER)
activePlugin.activeTreatments.addToHistoryTempBasal(tempBasal)
// val tempBasal = TemporaryBasal(injector) //
// .date(System.currentTimeMillis()) //
// .duration(0) //
// .source(Source.USER)
//
// activePlugin.activeTreatments.addToHistoryTempBasal(tempBasal)
// TODO need to find solution for this !?
// val tempData = PumpDbEntryTBR(absoluteRate, true, durationInMinutes, tbrType)
//
// pumpSyncStorage.addTemporaryBasalRateWithTempId(tempData, true, this)
val tempData = PumpDbEntryTBR(0.0, true, 0, TemporaryBasalType.NORMAL)
pumpSyncStorage.addTemporaryBasalRateWithTempId(tempData, true, this)
PumpEnactResult(injector).success(true).enacted(true) //
.isTempCancel(true)

View file

@ -26,7 +26,6 @@ import info.nightscout.androidaps.plugins.pump.medtronic.defs.PumpBolusType
import info.nightscout.androidaps.plugins.pump.medtronic.driver.MedtronicPumpStatus
import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicConst
import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil
import info.nightscout.androidaps.utils.Round
import info.nightscout.androidaps.utils.sharedPreferences.SP
import org.apache.commons.lang3.StringUtils
import org.joda.time.LocalDateTime
@ -579,23 +578,24 @@ class MedtronicHistoryData @Inject constructor(
entryList.removeAt(0)
}
}
val oldestTimestamp = getOldestTimestamp(entryList)
val entriesFromHistory = getDatabaseEntriesByLastTimestamp(oldestTimestamp, ProcessHistoryRecord.TBR)
val tbrRecords = pumpSyncStorage.getTBRs()
aapsLogger.debug(LTag.PUMP, String.format(Locale.ENGLISH, ProcessHistoryRecord.TBR.description + " List (before filter): %s, FromDb=%s", gson.toJson(entryList),
gson.toJson(entriesFromHistory)))
gson.toJson(tbrRecords)))
var processDTO: TempBasalProcessDTO? = null
val processList: MutableList<TempBasalProcessDTO> = ArrayList()
val processList: MutableList<TempBasalProcessDTO> = mutableListOf()
for (treatment in entryList) {
val tbr2 = treatment.getDecodedDataEntry("Object") as TempBasalPair?
if (tbr2!!.isCancelTBR) {
if (processDTO != null) {
processDTO.itemTwo = treatment
processDTO.cancelPresent = true
if (readOldItem) {
processDTO.processOperation = TempBasalProcessDTO.Operation.Edit
readOldItem = false
}
} else {
aapsLogger.error("processDTO was null - shouldn't happen. ItemTwo=$treatment")
aapsLogger.warn(LTag.PUMP,"processDTO was null - shouldn't happen, ignoring item. ItemTwo=$treatment")
}
} else {
if (processDTO != null) {
@ -609,41 +609,152 @@ class MedtronicHistoryData @Inject constructor(
if (processDTO != null) {
processList.add(processDTO)
}
if (isCollectionNotEmpty(processList)) {
if (processList.isNotEmpty()) {
for (tempBasalProcessDTO in processList) {
if (tempBasalProcessDTO.processOperation === TempBasalProcessDTO.Operation.Edit) {
// edit
val tempBasal = findTempBasalWithPumpId(tempBasalProcessDTO.itemOne!!.pumpId!!, entriesFromHistory)
if (tempBasal != null) {
tempBasal.durationInMinutes = tempBasalProcessDTO.duration
// TODO pumpSync - createOrUpdate(tempBasal)
databaseHelper.createOrUpdate(tempBasal)
aapsLogger.debug(LTag.PUMP, String.format(Locale.ENGLISH, "Edit " + ProcessHistoryRecord.TBR.description + " - (entryFromDb=%s) ", tempBasal))
} else {
aapsLogger.error(LTag.PUMP, "TempBasal not found. Item: " + tempBasalProcessDTO.itemOne)
}
val entryWithTempId = findDbEntry(tempBasalProcessDTO.itemOne, tbrRecords)
val tbrEntry = tempBasalProcessDTO.itemOne!!.getDecodedDataEntry("Object") as TempBasalPair
removeCancelTBRTemporaryRecord(tempBasalProcessDTO, tbrRecords) // TODO
if (entryWithTempId!=null) {
val result = pumpSync.syncTemporaryBasalWithTempId(
tryToGetByLocalTime(tempBasalProcessDTO.atechDateTime),
tbrEntry.insulinRate,
tempBasalProcessDTO.duration * 60L * 1000L,
!tbrEntry.isPercent,
entryWithTempId.temporaryId,
PumpSync.TemporaryBasalType.NORMAL,
tempBasalProcessDTO.pumpId,
medtronicPumpStatus.pumpType,
medtronicPumpStatus.serialNumber!!)
aapsLogger.debug(LTag.PUMP, String.format(Locale.ENGLISH, "syncTemporaryBasalWithTempId [date=%d, temporaryId=%d, pumpId=%d, rate=%.2f %s, duration=%d, pumpSerial=%s] - Result: %b",
tempBasalProcessDTO.atechDateTime, entryWithTempId.temporaryId, tempBasalProcessDTO.pumpId,
tbrEntry.insulinRate, (if (tbrEntry.isPercent) "%" else "U"), tempBasalProcessDTO.duration,
medtronicPumpStatus.serialNumber!!, result))
pumpSyncStorage.removeTemporaryBasalWithTemporaryId(entryWithTempId.temporaryId)
} else {
// add
val treatment = tempBasalProcessDTO.itemOne
val tbr2 = treatment!!.decodedData!!["Object"] as TempBasalPair?
tbr2!!.durationMinutes = tempBasalProcessDTO.duration
val tempBasal = findTempBasalWithPumpId(tempBasalProcessDTO.itemOne!!.pumpId!!, entriesFromHistory)
if (tempBasal == null) {
val treatmentDb = findDbEntry_Old(treatment, entriesFromHistory)
aapsLogger.debug(LTag.PUMP, String.format(Locale.ENGLISH, "Add " + ProcessHistoryRecord.TBR.description + " %s - (entryFromDb=%s) ", treatment, treatmentDb))
addTBR(treatment, treatmentDb as TemporaryBasal?)
} else {
// this shouldn't happen
if (tempBasal.durationInMinutes != tempBasalProcessDTO.duration) {
aapsLogger.debug(LTag.PUMP, "Found entry with wrong duration (shouldn't happen)... updating")
tempBasal.durationInMinutes = tempBasalProcessDTO.duration
}
}
} // if
val result = pumpSync.syncTemporaryBasalWithPumpId(
tryToGetByLocalTime(tempBasalProcessDTO.atechDateTime),
tbrEntry.insulinRate,
tempBasalProcessDTO.duration * 60L * 1000L,
!tbrEntry.isPercent,
PumpSync.TemporaryBasalType.NORMAL,
tempBasalProcessDTO.pumpId,
medtronicPumpStatus.pumpType,
medtronicPumpStatus.serialNumber!!)
aapsLogger.debug(LTag.PUMP, String.format(Locale.ENGLISH, "syncTemporaryBasalWithPumpId [date=%d, pumpId=%d, rate=%.2f %s, duration=%d, pumpSerial=%s] - Result: %b",
tempBasalProcessDTO.atechDateTime, tempBasalProcessDTO.pumpId,
tbrEntry.insulinRate, (if (tbrEntry.isPercent) "%" else "U"), tempBasalProcessDTO.duration,
medtronicPumpStatus.serialNumber!!, result))
}
} // for
} // collection
}
private fun removeCancelTBRTemporaryRecord(tempBasalProcessDTO: TempBasalProcessDTO, tbrRecords: MutableList<PumpDbEntry>) {
//fun syncTemporaryBasalWithPumpId(timestamp: Long, rate: Double, duration: Long, isAbsolute: Boolean, type: PumpSync.TemporaryBasalType?, pumpId: Long, pumpType: PumpType, pumpSerial: String): Boolean
if (tempBasalProcessDTO.cancelPresent) {
//val dateTime : Long = DateTimeUtil.getMillisFromATDWithAddedMinutes(tempBasalProcessDTO.atechDateTime, tempBasalProcessDTO.duration)
val dbEntry = findDbEntry(tempBasalProcessDTO.itemTwo!!, tbrRecords)
if (dbEntry!=null) {
if (dbEntry.tbrData!!.durationInMinutes == 0) {
pumpSync.invalidateTemporaryBasal(dbEntry.temporaryId) // TODO fix
}
}
//
}
}
// private fun processTBREntries_Old(entryList: MutableList<PumpHistoryEntry>) {
// Collections.reverse(entryList)
// val tbr = entryList[0].getDecodedDataEntry("Object") as TempBasalPair?
// var readOldItem = false
// if (tbr!!.isCancelTBR) {
// val oneMoreEntryFromHistory = getOneMoreEntryFromHistory(PumpHistoryEntryType.TempBasalCombined)
// if (oneMoreEntryFromHistory != null) {
// entryList.add(0, oneMoreEntryFromHistory)
// readOldItem = true
// } else {
// entryList.removeAt(0)
// }
// }
// val oldestTimestamp = getOldestTimestamp(entryList)
// val entriesFromHistory = getDatabaseEntriesByLastTimestamp(oldestTimestamp, ProcessHistoryRecord.TBR)
// aapsLogger.debug(LTag.PUMP, String.format(Locale.ENGLISH, ProcessHistoryRecord.TBR.description + " List (before filter): %s, FromDb=%s", gson.toJson(entryList),
// gson.toJson(entriesFromHistory)))
// var processDTO: TempBasalProcessDTO? = null
// val processList: MutableList<TempBasalProcessDTO> = ArrayList()
// for (treatment in entryList) {
// val tbr2 = treatment.getDecodedDataEntry("Object") as TempBasalPair?
// if (tbr2!!.isCancelTBR) {
// if (processDTO != null) {
// processDTO.itemTwo = treatment
// if (readOldItem) {
// processDTO.processOperation = TempBasalProcessDTO.Operation.Edit
// readOldItem = false
// }
// } else {
// aapsLogger.error("processDTO was null - shouldn't happen. ItemTwo=$treatment")
// }
// } else {
// if (processDTO != null) {
// processList.add(processDTO)
// }
// processDTO = TempBasalProcessDTO()
// processDTO.itemOne = treatment
// processDTO.processOperation = TempBasalProcessDTO.Operation.Add
// }
// }
// if (processDTO != null) {
// processList.add(processDTO)
// }
// if (isCollectionNotEmpty(processList)) {
// for (tempBasalProcessDTO in processList) {
// if (tempBasalProcessDTO.processOperation === TempBasalProcessDTO.Operation.Edit) {
// // edit
// val tempBasal = findTempBasalWithPumpId(tempBasalProcessDTO.itemOne!!.pumpId!!, entriesFromHistory)
// if (tempBasal != null) {
// tempBasal.durationInMinutes = tempBasalProcessDTO.duration
// // pumpSync - createOrUpdate(tempBasal)
// databaseHelper.createOrUpdate(tempBasal)
// aapsLogger.debug(LTag.PUMP, String.format(Locale.ENGLISH, "Edit " + ProcessHistoryRecord.TBR.description + " - (entryFromDb=%s) ", tempBasal))
// } else {
// aapsLogger.error(LTag.PUMP, "TempBasal not found. Item: " + tempBasalProcessDTO.itemOne)
// }
// } else {
// // add
// val treatment = tempBasalProcessDTO.itemOne
// val tbr2 = treatment!!.decodedData!!["Object"] as TempBasalPair?
// tbr2!!.durationMinutes = tempBasalProcessDTO.duration
// val tempBasal = findTempBasalWithPumpId(tempBasalProcessDTO.itemOne!!.pumpId!!, entriesFromHistory)
// if (tempBasal == null) {
// val treatmentDb = findDbEntry_Old(treatment, entriesFromHistory)
// aapsLogger.debug(LTag.PUMP, String.format(Locale.ENGLISH, "Add " + ProcessHistoryRecord.TBR.description + " %s - (entryFromDb=%s) ", treatment, treatmentDb))
// addTBR(treatment, treatmentDb as TemporaryBasal?)
// } else {
// // this shouldn't happen
// if (tempBasal.durationInMinutes != tempBasalProcessDTO.duration) {
// aapsLogger.debug(LTag.PUMP, "Found entry with wrong duration (shouldn't happen)... updating")
// tempBasal.durationInMinutes = tempBasalProcessDTO.duration
// }
// }
// } // if
// } // for
// } // collection
// }
private fun findTempBasalWithPumpId(pumpId: Long, entriesFromHistory: List<DbObjectBase>): TemporaryBasal? {
for (dbObjectBase in entriesFromHistory) {
val tbr = dbObjectBase as TemporaryBasal

View file

@ -4,9 +4,17 @@ import info.nightscout.androidaps.plugins.pump.common.utils.DateTimeUtil
import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.pump.PumpHistoryEntry
class TempBasalProcessDTO {
@JvmField var itemOne: PumpHistoryEntry? = null
@JvmField var itemTwo: PumpHistoryEntry? = null
@JvmField var processOperation = Operation.None
var itemOne: PumpHistoryEntry? = null
var itemTwo: PumpHistoryEntry? = null
var processOperation = Operation.None
var cancelPresent: Boolean = false
val atechDateTime: Long
get() = if (itemOne==null) 0L else itemOne!!.atechDateTime!!
val pumpId: Long
get() = if (itemOne==null) 0L else itemOne!!.pumpId!!
val duration: Int
get() = if (itemTwo == null) {
val tbr = itemOne!!.getDecodedDataEntry("Object") as TempBasalPair?