- changes after comments

This commit is contained in:
Andy Rozman 2021-05-26 20:16:17 +01:00
parent b40f8b79d1
commit 766b2b4bea
9 changed files with 24 additions and 428 deletions

View file

@ -111,7 +111,7 @@ android {
defaultConfig {
multiDexEnabled true
versionCode 1500
version "2.8.2.1"
version "2.8.2.1-dev-e5"
buildConfigField "String", "VERSION", '"' + version + '"'
buildConfigField "String", "BUILDVERSION", '"' + generateGitBuild() + '-' + generateDate() + '"'
buildConfigField "String", "REMOTE", '"' + generateGitRemote() + '"'

View file

@ -1,343 +0,0 @@
package info.nightscout.androidaps.plugins.treatments;
import android.content.Context;
import android.os.Bundle;
import com.google.firebase.analytics.FirebaseAnalytics;
import java.util.List;
import java.util.stream.Collectors;
import javax.inject.Inject;
import javax.inject.Singleton;
import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.activities.ErrorHelperActivity;
import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.database.AppRepository;
import info.nightscout.androidaps.db.ExtendedBolus;
import info.nightscout.androidaps.db.Source;
import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.db.Treatment;
import info.nightscout.androidaps.interfaces.ActivePlugin;
import info.nightscout.androidaps.interfaces.DatabaseHelperInterface;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginDescription;
import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.interfaces.ProfileFunction;
import info.nightscout.androidaps.interfaces.TreatmentServiceInterface;
import info.nightscout.androidaps.interfaces.TreatmentsInterface;
import info.nightscout.androidaps.interfaces.UpdateReturn;
import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.plugins.bus.RxBusWrapper;
<<<<<<< HEAD
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload;
import info.nightscout.androidaps.plugins.pump.common.defs.PumpType;
import info.nightscout.androidaps.plugins.pump.medtronic.MedtronicPumpPlugin;
import info.nightscout.androidaps.plugins.pump.medtronic.data.MedtronicHistoryData;
=======
>>>>>>> dev2_dana_combo_only
import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.resources.ResourceHelper;
import info.nightscout.androidaps.utils.rx.AapsSchedulers;
import info.nightscout.androidaps.utils.sharedPreferences.SP;
import io.reactivex.disposables.CompositeDisposable;
@Singleton
public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface {
<<<<<<< HEAD
private final Context context;
private final AapsSchedulers aapsSchedulers;
=======
>>>>>>> dev2_dana_combo_only
private final SP sp;
private final RxBusWrapper rxBus;
private final ResourceHelper resourceHelper;
private final ProfileFunction profileFunction;
private final ActivePlugin activePlugin;
private final FabricPrivacy fabricPrivacy;
private final DateUtil dateUtil;
private final DatabaseHelperInterface databaseHelper;
private final AppRepository repository;
private final CompositeDisposable disposable = new CompositeDisposable();
protected TreatmentServiceInterface service;
private final boolean useNewPumpSync = false;
@Inject
public TreatmentsPlugin(
HasAndroidInjector injector,
AAPSLogger aapsLogger,
RxBusWrapper rxBus,
AapsSchedulers aapsSchedulers,
ResourceHelper resourceHelper,
Context context,
SP sp,
ProfileFunction profileFunction,
ActivePlugin activePlugin,
FabricPrivacy fabricPrivacy,
DateUtil dateUtil,
DatabaseHelperInterface databaseHelper,
AppRepository repository
) {
super(new PluginDescription()
.mainType(PluginType.TREATMENT)
.fragmentClass(TreatmentsFragment.class.getName())
.pluginIcon(R.drawable.ic_treatments)
.pluginName(R.string.treatments)
.shortName(R.string.treatments_shortname)
.alwaysEnabled(true)
.description(R.string.description_treatments)
.setDefault(),
aapsLogger, resourceHelper, injector
);
this.resourceHelper = resourceHelper;
this.context = context;
this.rxBus = rxBus;
this.sp = sp;
this.profileFunction = profileFunction;
this.activePlugin = activePlugin;
this.fabricPrivacy = fabricPrivacy;
this.dateUtil = dateUtil;
this.databaseHelper = databaseHelper;
this.repository = repository;
}
@Override
protected void onStart() {
this.service = new TreatmentService(getInjector());
super.onStart();
// disposable.add(rxBus
// .toObservable(EventReloadProfileSwitchData.class)
// .observeOn(aapsSchedulers.getIo())
// .subscribe(event -> initializeProfileSwitchData(range()),
// fabricPrivacy::logException
// ));
}
@Override
protected void onStop() {
disposable.clear();
super.onStop();
}
@Override
public TreatmentServiceInterface getService() {
return this.service;
}
protected long range() {
double dia = Constants.defaultDIA;
if (profileFunction.getProfile() != null)
dia = profileFunction.getProfile().getDia();
return (long) (60 * 60 * 1000L * (24 + dia));
}
/**
* Returns all Treatments after specified timestamp. Also returns invalid entries (required to
* map "Fill Cannula" entries to history (and not to add double bolus for it)
*
* @param fromTimestamp
* @return
*/
@Deprecated
@Override
public List<Treatment> getTreatmentsFromHistoryAfterTimestamp(long fromTimestamp) {
return repository.getBolusesIncludingInvalidFromTimeToTime(fromTimestamp, dateUtil.now(), true)
.blockingGet()
.stream()
.map(bolus -> new Treatment(getInjector(), bolus))
.collect(Collectors.toList());
/*
List<Treatment> in5minback = new ArrayList<>();
long time = System.currentTimeMillis();
synchronized (treatments) {
// getAapsLogger().debug(MedtronicHistoryData.doubleBolusDebug, LTag.DATATREATMENTS, "DoubleBolusDebug: AllTreatmentsInDb: " + new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create().toJson(treatments));
for (Treatment t : treatments) {
if (t.date >= fromTimestamp && t.date <= time)
in5minback.add(t);
}
// getAapsLogger().debug(MedtronicHistoryData.doubleBolusDebug, LTag.DATATREATMENTS, "DoubleBolusDebug: FilteredTreatments: AfterTime={}, Items={} " + fromTimestamp + " " + new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create().toJson(in5minback));
return in5minback;
}
*/
}
/*
@Override
public long getLastBolusTime() {
Treatment last = getService().getLastBolus(false);
if (last == null) {
getAapsLogger().debug(LTag.DATATREATMENTS, "Last bolus time: NOTHING FOUND");
return 0;
} else {
getAapsLogger().debug(LTag.DATATREATMENTS, "Last bolus time: " + dateUtil.dateAndTimeString(last.date));
return last.date;
}
}
public long getLastBolusTime(boolean excludeSMB) {
Treatment last = getService().getLastBolus(excludeSMB);
if (last == null) {
getAapsLogger().debug(LTag.DATATREATMENTS, "Last manual bolus time: NOTHING FOUND");
return 0;
} else {
getAapsLogger().debug(LTag.DATATREATMENTS, "Last manual bolus time: " + dateUtil.dateAndTimeString(last.date));
return last.date;
}
}
public long getLastCarbTime() {
Treatment last = getService().getLastCarb();
if (last == null) {
getAapsLogger().debug(LTag.DATATREATMENTS, "Last Carb time: NOTHING FOUND");
return 0;
} else {
getAapsLogger().debug(LTag.DATATREATMENTS, "Last Carb time: " + dateUtil.dateAndTimeString(last.date));
return last.date;
}
}
*/
@Deprecated
@Override
public boolean addToHistoryExtendedBolus(ExtendedBolus extendedBolus) {
throw new IllegalStateException("Migrate to new DB");
//log.debug("Adding new ExtentedBolus record" + extendedBolus.log());
/*
boolean newRecordCreated = databaseHelper.createOrUpdate(extendedBolus);
if (newRecordCreated) {
if (extendedBolus.durationInMinutes == 0) {
if (activePlugin.getActivePump().isFakingTempsByExtendedBoluses())
nsUpload.uploadTempBasalEnd(extendedBolus.date, true, extendedBolus.pumpId);
else
nsUpload.uploadExtendedBolusEnd(extendedBolus.date, extendedBolus.pumpId);
} else if (activePlugin.getActivePump().isFakingTempsByExtendedBoluses())
nsUpload.uploadTempBasalStartAbsolute(new TemporaryBasal(extendedBolus), extendedBolus.insulin);
else
nsUpload.uploadExtendedBolus(extendedBolus);
}
return newRecordCreated;
*/
}
@Deprecated
@Override
public boolean addToHistoryTempBasal(TemporaryBasal tempBasal) {
if (useNewPumpSync) {
throw new IllegalStateException("Migrate to new DB");
} else {
getAapsLogger().error("!!! addToHistoryTempBasal: Need to migrate to new DB");
}
//log.debug("Adding new TemporaryBasal record" + tempBasal.toString());
boolean newRecordCreated = databaseHelper.createOrUpdate(tempBasal);
if (newRecordCreated) {
// if (tempBasal.durationInMinutes == 0)
// nsUpload.uploadTempBasalEnd(tempBasal.date, false, tempBasal.pumpId);
// else if (tempBasal.isAbsolute)
// nsUpload.uploadTempBasalStartAbsolute(tempBasal, null);
// else
// nsUpload.uploadTempBasalStartPercent(tempBasal, profileFunction.getProfile(tempBasal.date));
}
return newRecordCreated;
}
@Deprecated
public TreatmentUpdateReturn createOrUpdateMedtronic(Treatment treatment, boolean fromNightScout) {
if (useNewPumpSync) {
throw new IllegalStateException("Migrate to new DB");
} else {
getAapsLogger().error("!!! createOrUpdateMedtronic: Need to migrate to new DB");
}
UpdateReturn resultRecord = getService().createOrUpdateMedtronic(treatment, fromNightScout);
return new TreatmentUpdateReturn(resultRecord.getSuccess(), resultRecord.getNewRecord());
}
// return true if new record is created
@Deprecated
@Override
public boolean addToHistoryTreatment(DetailedBolusInfo detailedBolusInfo, boolean allowUpdate) {
if (useNewPumpSync) {
throw new IllegalStateException("Migrate to new DB");
} else {
getAapsLogger().error("!!! addToHistoryTreatment: Need to migrate to new DB");
}
boolean medtronicPump = activePlugin.getActivePump() instanceof MedtronicPumpPlugin;
getAapsLogger().debug(MedtronicHistoryData.doubleBolusDebug, LTag.DATATREATMENTS, "DoubleBolusDebug: addToHistoryTreatment::isMedtronicPump={} " + medtronicPump);
Treatment treatment = new Treatment();
treatment.date = detailedBolusInfo.timestamp;
treatment.source = (detailedBolusInfo.getPumpType() == PumpType.USER) ? Source.USER : Source.PUMP;
treatment.pumpId = detailedBolusInfo.getBolusPumpId() != null ? detailedBolusInfo.getBolusPumpId() : 0;
treatment.insulin = detailedBolusInfo.insulin;
treatment.isValid = detailedBolusInfo.getBolusType() != DetailedBolusInfo.BolusType.PRIMING;
treatment.isSMB = detailedBolusInfo.getBolusType() == DetailedBolusInfo.BolusType.SMB;
if (detailedBolusInfo.carbTime == 0)
treatment.carbs = detailedBolusInfo.carbs;
treatment.mealBolus = treatment.carbs > 0;
// treatment.boluscalc = detailedBolusInfo.boluscalc != null ? detailedBolusInfo.boluscalc.toString() : null;
treatment.boluscalc = null;
UpdateReturn creatOrUpdateResult;
getAapsLogger().debug(medtronicPump && MedtronicHistoryData.doubleBolusDebug, LTag.DATATREATMENTS, "DoubleBolusDebug: addToHistoryTreatment::treatment={} " + treatment);
if (!medtronicPump)
creatOrUpdateResult = getService().createOrUpdate(treatment);
else
creatOrUpdateResult = getService().createOrUpdateMedtronic(treatment, false);
boolean newRecordCreated = creatOrUpdateResult.getNewRecord();
//log.debug("Adding new Treatment record" + treatment.toString());
if (detailedBolusInfo.carbTime != 0) {
Treatment carbsTreatment = new Treatment();
carbsTreatment.source = (detailedBolusInfo.getPumpType() == PumpType.USER) ? Source.USER : Source.PUMP;
carbsTreatment.pumpId = detailedBolusInfo.getCarbsPumpId() != null ? detailedBolusInfo.getCarbsPumpId() : 0; // but this should never happen
carbsTreatment.date = detailedBolusInfo.timestamp + detailedBolusInfo.carbTime * 60 * 1000L + 1000L; // add 1 sec to make them different records
carbsTreatment.carbs = detailedBolusInfo.carbs;
getAapsLogger().debug(medtronicPump && MedtronicHistoryData.doubleBolusDebug, LTag.DATATREATMENTS, "DoubleBolusDebug: carbTime!=0, creating second treatment. CarbsTreatment={}" + carbsTreatment);
if (!medtronicPump)
getService().createOrUpdate(carbsTreatment);
else
getService().createOrUpdateMedtronic(carbsTreatment, false);
//log.debug("Adding new Treatment record" + carbsTreatment);
}
getAapsLogger().error("nsUpload.uploadTreatmentRecord(detailedBolusInfo) not possible.");
// if (newRecordCreated && detailedBolusInfo.getBolusType() != DetailedBolusInfo.BolusType.PRIMING)
// nsUpload.uploadTreatmentRecord(detailedBolusInfo);
if (!allowUpdate && !creatOrUpdateResult.getSuccess()) {
getAapsLogger().error("Treatment could not be added to DB", new Exception());
String status = String.format(resourceHelper.gs(R.string.error_adding_treatment_message), treatment.insulin, (int) treatment.carbs, dateUtil.dateAndTimeString(treatment.date));
ErrorHelperActivity.Companion.runAlarm(context, status, resourceHelper.gs(R.string.error_adding_treatment_title), R.raw.error);
Bundle bundle = new Bundle();
bundle.putString(FirebaseAnalytics.Param.ITEM_LIST_ID, "TreatmentClash");
bundle.putString(FirebaseAnalytics.Param.ITEM_LIST_NAME, status);
fabricPrivacy.logCustom(bundle);
}
return newRecordCreated;
}
}

View file

@ -1,4 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="pump_commerror_label">Connection Error</string>
</resources>

View file

@ -1,4 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="pump_commerror_label">Connection Error</string>
</resources>

View file

@ -108,7 +108,8 @@ class MedtronicPumpPlugin @Inject constructor(
private var lastPumpHistoryEntry: PumpHistoryEntry? = null
private val busyTimestamps: MutableList<Long> = ArrayList()
private var hasTimeDateOrTimeZoneChanged = false
private val usePumpSync = false
private var isBusy = false
private val displayConnectionMessages = false
override fun onStart() {
aapsLogger.debug(LTag.PUMP, deviceID() + " started.")
@ -1125,7 +1126,7 @@ class MedtronicPumpPlugin @Inject constructor(
}
override fun executeCustomAction(customActionType: CustomActionType) {
val mcat = customActionType as MedtronicCustomActionType
val mcat = customActionType as? MedtronicCustomActionType
when (mcat) {
MedtronicCustomActionType.WakeUpAndTune -> {
if (rileyLinkMedtronicService.verifyConfiguration()) {
@ -1144,6 +1145,10 @@ class MedtronicPumpPlugin @Inject constructor(
MedtronicCustomActionType.ResetRileyLinkConfiguration -> {
serviceTaskExecutor.startTask(ResetRileyLinkConfigurationTask(injector))
}
null -> {
}
}
}
@ -1165,12 +1170,4 @@ class MedtronicPumpPlugin @Inject constructor(
refreshCustomActionsList()
}
companion object {
var isBusy = false
}
init {
displayConnectionMessages = false
}
}

View file

@ -444,32 +444,6 @@ class MedtronicCommunicationManager // This empty constructor must be kept, oth
}
}
// private fun <T> sendAndGetResponseWithCheck(commandType: MedtronicCommandType, bodyData: ByteArray, clazz: Class<T>): T? {
// aapsLogger.debug(LTag.PUMPCOMM, "getDataFromPump: $commandType")
// for (retries in 0 until MAX_COMMAND_TRIES) {
// try {
// val response = sendAndGetResponse(commandType, bodyData, DEFAULT_TIMEOUT + DEFAULT_TIMEOUT * retries)
// val check = checkResponseContent(response, commandType.commandDescription, commandType.expectedLength)
// if (check == null) {
// val dataResponse = medtronicConverter!!.convertResponse(medtronicPumpPlugin!!.pumpDescription.pumpType, commandType, response.rawContent) as T?
// if (dataResponse != null) {
// errorResponse = null
// aapsLogger.debug(LTag.PUMPCOMM, String.format(Locale.ENGLISH, "Converted response for %s is %s.", commandType.name, dataResponse))
// return dataResponse
// } else {
// errorResponse = "Error decoding response."
// }
// } else {
// errorResponse = check
// // return null;
// }
// } catch (e: RileyLinkCommunicationException) {
// aapsLogger.warn(LTag.PUMPCOMM, String.format(Locale.ENGLISH, "Error getting response from RileyLink (error=%s, retry=%d)", e.message, retries + 1))
// }
// }
// return null
// }
private fun checkResponseContent(response: PumpMessage, method: String, expectedLength: Int): String? {
if (!response.isValid) {
val responseData = String.format("%s: Invalid response.", method)

View file

@ -62,7 +62,7 @@ abstract class MedtronicHistoryDecoder<T : MedtronicHistoryEntry?>(var aapsLogge
}
}
protected fun addToStatistics(pumpHistoryEntry: MedtronicHistoryEntryInterface, status: RecordDecodeStatus?, opCode: Int?) {
protected fun addToStatistics(pumpHistoryEntry: MedtronicHistoryEntryInterface, status: RecordDecodeStatus, opCode: Int?) {
if (!statisticsEnabled) return
if (opCode != null) {
if (!unknownOpCodes.containsKey(opCode)) {

View file

@ -67,11 +67,6 @@ abstract class MedtronicHistoryEntry : MedtronicHistoryEntryInterface {
field = value
}
// fun setLinkedObject(linkedObject: Any?) {
// linked = true
// this.linkedObject = linkedObject
// }
abstract fun generatePumpId(): Long
abstract fun isEntryTypeSet(): Boolean
@ -126,10 +121,6 @@ abstract class MedtronicHistoryEntry : MedtronicHistoryEntryInterface {
val isNoDataEntry: Boolean
get() = sizes[0] == 2 && sizes[1] == 5 && sizes[2] == 0
// fun getDecodedData(): Map<String, Any?>? {
// return decodedData
// }
fun getDecodedDataEntry(key: String?): Any? {
return if (decodedData.containsKey(key)) decodedData[key] else null
}

View file

@ -165,8 +165,6 @@ enum class MedtronicCommandType {
}
init {
RFPowerOn.maxAllowedTime = 17000
RFPowerOn.allowedRetries = 0
RFPowerOn.recordLength = 0
RFPowerOn.minimalBufferSizeToStartReading = 1
for (medtronicCommandType in values()) {
@ -183,7 +181,8 @@ enum class MedtronicCommandType {
var resourceId: Int? = null
private set
var allowedRetries = 2
var maxAllowedTime = 2000
//var maxAllowedTime = 2000
var parameterType: MinimedCommandParameterType? = null
var minimalBufferSizeToStartReading = 14
var expectedLength = 0
@ -201,14 +200,21 @@ enum class MedtronicCommandType {
}
// NEW
constructor(code: Int, description: String, devices: MedtronicDeviceType?, //
parameterType: MinimedCommandParameterType?, expectedLength: Int) : this(code, description, devices, parameterType, 64, 1, expectedLength, null) {
}
// constructor(code: Int,
// description: String,
// devices: MedtronicDeviceType?, //
// parameterType: MinimedCommandParameterType?,
// expectedLength: Int) : this(code, description, devices, parameterType, 64, 1, expectedLength, null) {
// }
// NEW
constructor(code: Int, description: String, devices: MedtronicDeviceType?, //
parameterType: MinimedCommandParameterType?, expectedLength: Int, resourceId: Int) : this(code, description, devices, parameterType, 64, 1, expectedLength, resourceId) {
}
// constructor(code: Int,
// description: String,
// devices: MedtronicDeviceType?, //
// parameterType: MinimedCommandParameterType?,
// expectedLength: Int,
// resourceId: Int) : this(code, description, devices, parameterType, 64, 1, expectedLength, resourceId) {
// }
// NEW
constructor(code: Int,
@ -222,7 +228,6 @@ enum class MedtronicCommandType {
commandCode = code.toByte()
commandDescription = description
this.devices = devices
this.recordLength = recordLength
maxRecords = max_recs
this.resourceId = resourceId
commandParametersCount = 0
@ -234,26 +239,6 @@ enum class MedtronicCommandType {
}
}
// @Deprecated("")
// constructor(code: Int, description: String, devices: MedtronicDeviceType?, //
// parameterType: MinimedCommandParameterType?, recordLength: Int, max_recs: Int, addy: Int, //
// addy_len: Int, cmd_type: Int, expectedLength: Int) {
// commandCode = code.toByte()
// commandDescription = description
// //this.targetType = targetType;
// this.devices = devices
// this.recordLength = recordLength
// maxRecords = max_recs
// command_type = cmd_type
// commandParametersCount = 0
// allowedRetries = 2
// this.parameterType = parameterType
// this.expectedLength = expectedLength
// if (this.parameterType == MinimedCommandParameterType.SubCommands) {
// minimalBufferSizeToStartReading = 200
// }
// }
override fun toString(): String {
return name
}