- refactorings kotlin !!

- moved 2 filed into pump-common module (newly created)
This commit is contained in:
Andy Rozman 2021-05-24 16:57:54 +01:00
parent fb5ff409f8
commit e24af3934f
27 changed files with 187 additions and 148 deletions

View file

@ -186,6 +186,7 @@ dependencies {
implementation project(':danars') implementation project(':danars')
implementation project(':danar') implementation project(':danar')
implementation project(':insight') implementation project(':insight')
implementation project(':pump-common')
implementation project(':rileylink') implementation project(':rileylink')
implementation project(':medtronic') implementation project(':medtronic')
implementation project(':omnipod-common') implementation project(':omnipod-common')

View file

@ -77,27 +77,36 @@ open class AppModule {
pumpSync: PumpSync, pumpSync: PumpSync,
sp: SP, sp: SP,
aapsLogger: AAPSLogger aapsLogger: AAPSLogger
): PumpSyncStorage { ): info.nightscout.androidaps.plugins.pump.common.sync.PumpSyncStorage {
return PumpSyncStorage(pumpSync, sp, aapsLogger) return info.nightscout.androidaps.plugins.pump.common.sync.PumpSyncStorage(pumpSync, sp, aapsLogger)
} }
@Module @Module
interface AppBindings { interface AppBindings {
@Binds fun bindContext(mainApp: MainApp): Context @Binds fun bindContext(mainApp: MainApp): Context
@Binds fun bindInjector(mainApp: MainApp): HasAndroidInjector @Binds fun bindInjector(mainApp: MainApp): HasAndroidInjector
@Binds fun bindActivePluginProvider(pluginStore: PluginStore): ActivePlugin @Binds fun bindActivePluginProvider(pluginStore: PluginStore): ActivePlugin
@Binds fun bindCommandQueueProvider(commandQueue: CommandQueue): CommandQueueProvider @Binds fun bindCommandQueueProvider(commandQueue: CommandQueue): CommandQueueProvider
@Binds fun bindConfigInterface(config: ConfigImpl): Config @Binds fun bindConfigInterface(config: ConfigImpl): Config
@Binds fun bindConfigBuilderInterface(configBuilderPlugin: ConfigBuilderPlugin): ConfigBuilder @Binds
fun bindConfigBuilderInterface(configBuilderPlugin: ConfigBuilderPlugin): ConfigBuilder
@Binds fun bindTreatmentsInterface(treatmentsPlugin: TreatmentsPlugin): TreatmentsInterface @Binds fun bindTreatmentsInterface(treatmentsPlugin: TreatmentsPlugin): TreatmentsInterface
@Binds fun bindDatabaseHelperInterface(databaseHelperProvider: DatabaseHelperProvider): DatabaseHelperInterface @Binds
@Binds fun bindNotificationHolderInterface(notificationHolder: NotificationHolderImpl): NotificationHolder fun bindDatabaseHelperInterface(databaseHelperProvider: DatabaseHelperProvider): DatabaseHelperInterface
@Binds fun bindImportExportPrefsInterface(importExportPrefs: ImportExportPrefsImpl): ImportExportPrefs @Binds
@Binds fun bindIconsProviderInterface(iconsProvider: IconsProviderImplementation): IconsProvider fun bindNotificationHolderInterface(notificationHolder: NotificationHolderImpl): NotificationHolder
@Binds
fun bindImportExportPrefsInterface(importExportPrefs: ImportExportPrefsImpl): ImportExportPrefs
@Binds
fun bindIconsProviderInterface(iconsProvider: IconsProviderImplementation): IconsProvider
@Binds fun bindLoopInterface(loopPlugin: LoopPlugin): LoopInterface @Binds fun bindLoopInterface(loopPlugin: LoopPlugin): LoopInterface
@Binds fun bindIobCobCalculatorInterface(iobCobCalculatorPlugin: IobCobCalculatorPlugin): IobCobCalculator @Binds
@Binds fun bindSmsCommunicatorInterface(smsCommunicatorPlugin: SmsCommunicatorPlugin): SmsCommunicator fun bindIobCobCalculatorInterface(iobCobCalculatorPlugin: IobCobCalculatorPlugin): IobCobCalculator
@Binds fun bindDataSyncSelector(dataSyncSelectorImplementation: DataSyncSelectorImplementation): DataSyncSelector @Binds
fun bindSmsCommunicatorInterface(smsCommunicatorPlugin: SmsCommunicatorPlugin): SmsCommunicator
@Binds
fun bindDataSyncSelector(dataSyncSelectorImplementation: DataSyncSelectorImplementation): DataSyncSelector
@Binds fun bindPumpSync(pumpSyncImplementation: PumpSyncImplementation): PumpSync @Binds fun bindPumpSync(pumpSyncImplementation: PumpSyncImplementation): PumpSync
} }

View file

@ -32,6 +32,7 @@ enum class PumpHistoryEntryGroup(val resourceId: Int) {
} }
companion object { companion object {
private var translatedList: MutableList<PumpHistoryEntryGroup>? = null private var translatedList: MutableList<PumpHistoryEntryGroup>? = null
private fun doTranslation(resourceHelper: ResourceHelper) { private fun doTranslation(resourceHelper: ResourceHelper) {
@ -43,9 +44,9 @@ enum class PumpHistoryEntryGroup(val resourceId: Int) {
} }
@JvmStatic @JvmStatic
fun getTranslatedList(resourceHelper: ResourceHelper): List<PumpHistoryEntryGroup>? { fun getTranslatedList(resourceHelper: ResourceHelper): List<PumpHistoryEntryGroup> {
if (translatedList == null) doTranslation(resourceHelper) if (translatedList == null) doTranslation(resourceHelper)
return translatedList return translatedList!!
} }
} }

View file

@ -16,5 +16,6 @@ android {
dependencies { dependencies {
implementation project(':core') implementation project(':core')
implementation project(':pump-common')
implementation project(':rileylink') implementation project(':rileylink')
} }

View file

@ -90,8 +90,8 @@ class MedtronicPumpPlugin @Inject constructor(
dateUtil: DateUtil, dateUtil: DateUtil,
aapsSchedulers: AapsSchedulers, aapsSchedulers: AapsSchedulers,
pumpSync: PumpSync, pumpSync: PumpSync,
pumpSyncStorage: PumpSyncStorage pumpSyncStorage: info.nightscout.androidaps.plugins.pump.common.sync.PumpSyncStorage
) : PumpPluginAbstract(PluginDescription() // ) : info.nightscout.androidaps.plugins.pump.common.PumpPluginAbstract(PluginDescription() //
.mainType(PluginType.PUMP) // .mainType(PluginType.PUMP) //
.fragmentClass(MedtronicFragment::class.java.name) // .fragmentClass(MedtronicFragment::class.java.name) //
.pluginIcon(R.drawable.ic_veo_128) .pluginIcon(R.drawable.ic_veo_128)
@ -101,7 +101,7 @@ class MedtronicPumpPlugin @Inject constructor(
.description(R.string.description_pump_medtronic), // .description(R.string.description_pump_medtronic), //
PumpType.MEDTRONIC_522_722, // we default to most basic model, correct model from config is loaded later PumpType.MEDTRONIC_522_722, // we default to most basic model, correct model from config is loaded later
injector, resourceHelper, aapsLogger, commandQueue, rxBus, activePlugin, sp, context, fabricPrivacy, dateUtil, aapsSchedulers, pumpSync, pumpSyncStorage injector, resourceHelper, aapsLogger, commandQueue, rxBus, activePlugin, sp, context, fabricPrivacy, dateUtil, aapsSchedulers, pumpSync, pumpSyncStorage
), Pump, RileyLinkPumpDevice, PumpSyncEntriesCreator { ), Pump, RileyLinkPumpDevice, info.nightscout.androidaps.plugins.pump.common.sync.PumpSyncEntriesCreator {
private lateinit var rileyLinkMedtronicService: RileyLinkMedtronicService private lateinit var rileyLinkMedtronicService: RileyLinkMedtronicService
@ -199,7 +199,7 @@ class MedtronicPumpPlugin @Inject constructor(
SystemClock.sleep(60000) SystemClock.sleep(60000)
if (this.isInitialized) { if (this.isInitialized) {
val statusRefresh = workWithStatusRefresh( val statusRefresh = workWithStatusRefresh(
StatusRefreshAction.GetData, null, null) StatusRefreshAction.GetData, null, null)!!
if (doWeHaveAnyStatusNeededRefereshing(statusRefresh)) { if (doWeHaveAnyStatusNeededRefereshing(statusRefresh)) {
if (!commandQueue.statusInQueue()) { if (!commandQueue.statusInQueue()) {
commandQueue.readStatus("Scheduled Status Refresh", null) commandQueue.readStatus("Scheduled Status Refresh", null)
@ -214,7 +214,7 @@ class MedtronicPumpPlugin @Inject constructor(
override val serviceClass: Class<*> override val serviceClass: Class<*>
get() = RileyLinkMedtronicService::class.java get() = RileyLinkMedtronicService::class.java
override val pumpStatusData: PumpStatus override val pumpStatusData: info.nightscout.androidaps.plugins.pump.common.data.PumpStatus
get() = medtronicPumpStatus get() = medtronicPumpStatus
override fun deviceID(): String { override fun deviceID(): String {
@ -334,7 +334,7 @@ class MedtronicPumpPlugin @Inject constructor(
private fun refreshAnyStatusThatNeedsToBeRefreshed() { private fun refreshAnyStatusThatNeedsToBeRefreshed() {
val statusRefresh = workWithStatusRefresh(StatusRefreshAction.GetData, null, val statusRefresh = workWithStatusRefresh(StatusRefreshAction.GetData, null,
null) null)!!
if (!doWeHaveAnyStatusNeededRefereshing(statusRefresh)) { if (!doWeHaveAnyStatusNeededRefereshing(statusRefresh)) {
return return
} }
@ -354,7 +354,7 @@ class MedtronicPumpPlugin @Inject constructor(
// execute // execute
val refreshTypesNeededToReschedule: MutableSet<MedtronicStatusRefreshType> = mutableSetOf() val refreshTypesNeededToReschedule: MutableSet<MedtronicStatusRefreshType> = mutableSetOf()
for ((key, value) in statusRefresh!!) { for ((key, value) in statusRefresh) {
if (value > 0 && System.currentTimeMillis() > value) { if (value > 0 && System.currentTimeMillis() > value) {
when (key) { when (key) {
MedtronicStatusRefreshType.PumpHistory -> { MedtronicStatusRefreshType.PumpHistory -> {
@ -389,8 +389,8 @@ class MedtronicPumpPlugin @Inject constructor(
if (resetTime) medtronicPumpStatus.setLastCommunicationToNow() if (resetTime) medtronicPumpStatus.setLastCommunicationToNow()
} }
private fun doWeHaveAnyStatusNeededRefereshing(statusRefresh: Map<MedtronicStatusRefreshType, Long>?): Boolean { private fun doWeHaveAnyStatusNeededRefereshing(statusRefresh: Map<MedtronicStatusRefreshType, Long>): Boolean {
for ((_, value) in statusRefresh!!) { for ((_, value) in statusRefresh) {
if (value > 0 && System.currentTimeMillis() > value) { if (value > 0 && System.currentTimeMillis() > value) {
return true return true
} }
@ -583,10 +583,10 @@ class MedtronicPumpPlugin @Inject constructor(
scheduleNextRefresh(MedtronicStatusRefreshType.PumpTime, 0) scheduleNextRefresh(MedtronicStatusRefreshType.PumpTime, 0)
} }
override fun deliverBolus(detailedBolusInfo: DetailedBolusInfo?): PumpEnactResult { override fun deliverBolus(detailedBolusInfo: DetailedBolusInfo): PumpEnactResult {
aapsLogger.info(LTag.PUMP, "MedtronicPumpPlugin::deliverBolus - " + BolusDeliveryType.DeliveryPrepared) aapsLogger.info(LTag.PUMP, "MedtronicPumpPlugin::deliverBolus - " + BolusDeliveryType.DeliveryPrepared)
setRefreshButtonEnabled(false) setRefreshButtonEnabled(false)
if (detailedBolusInfo!!.insulin > medtronicPumpStatus.reservoirRemainingUnits) { if (detailedBolusInfo.insulin > medtronicPumpStatus.reservoirRemainingUnits) {
return PumpEnactResult(injector) // return PumpEnactResult(injector) //
.success(false) // .success(false) //
.enacted(false) // .enacted(false) //
@ -621,7 +621,12 @@ class MedtronicPumpPlugin @Inject constructor(
setRefreshButtonEnabled(true) setRefreshButtonEnabled(true)
// LOG.debug("MedtronicPumpPlugin::deliverBolus - Response: {}", response); // LOG.debug("MedtronicPumpPlugin::deliverBolus - Response: {}", response);
if (response!!) { return if (response == null || !response) {
PumpEnactResult(injector) //
.success(bolusDeliveryType == BolusDeliveryType.CancelDelivery) //
.enacted(false) //
.comment(R.string.medtronic_cmd_bolus_could_not_be_delivered)
} else {
if (bolusDeliveryType == BolusDeliveryType.CancelDelivery) { if (bolusDeliveryType == BolusDeliveryType.CancelDelivery) {
// LOG.debug("MedtronicPumpPlugin::deliverBolus - Delivery Canceled after Bolus started."); // LOG.debug("MedtronicPumpPlugin::deliverBolus - Delivery Canceled after Bolus started.");
Thread(Runnable { Thread(Runnable {
@ -648,11 +653,6 @@ class MedtronicPumpPlugin @Inject constructor(
.enacted(true) // .enacted(true) //
.bolusDelivered(detailedBolusInfo.insulin) // .bolusDelivered(detailedBolusInfo.insulin) //
.carbsDelivered(detailedBolusInfo.carbs) .carbsDelivered(detailedBolusInfo.carbs)
} else {
PumpEnactResult(injector) //
.success(bolusDeliveryType == BolusDeliveryType.CancelDelivery) //
.enacted(false) //
.comment(R.string.medtronic_cmd_bolus_could_not_be_delivered)
} }
} finally { } finally {
finishAction("Bolus") finishAction("Bolus")
@ -739,13 +739,13 @@ class MedtronicPumpPlugin @Inject constructor(
// CANCEL // CANCEL
val responseTask2 = rileyLinkMedtronicService.medtronicUIComm.executeCommand(MedtronicCommandType.CancelTBR) val responseTask2 = rileyLinkMedtronicService.medtronicUIComm.executeCommand(MedtronicCommandType.CancelTBR)
val response = responseTask2.result as Boolean? val response = responseTask2.result as Boolean?
if (response!!) { if (response == null || !response) {
aapsLogger.info(LTag.PUMP, logPrefix + "setTempBasalAbsolute - Current TBR cancelled.")
} else {
aapsLogger.error(logPrefix + "setTempBasalAbsolute - Cancel TBR failed.") aapsLogger.error(logPrefix + "setTempBasalAbsolute - Cancel TBR failed.")
finishAction("TBR") finishAction("TBR")
return PumpEnactResult(injector).success(false).enacted(false) return PumpEnactResult(injector).success(false).enacted(false)
.comment(R.string.medtronic_cmd_cant_cancel_tbr_stop_op) .comment(R.string.medtronic_cmd_cant_cancel_tbr_stop_op)
} else {
aapsLogger.info(LTag.PUMP, logPrefix + "setTempBasalAbsolute - Current TBR cancelled.")
} }
} }
@ -763,7 +763,7 @@ class MedtronicPumpPlugin @Inject constructor(
medtronicPumpStatus.tempBasalAmount = absoluteRate medtronicPumpStatus.tempBasalAmount = absoluteRate
medtronicPumpStatus.tempBasalLength = durationInMinutes medtronicPumpStatus.tempBasalLength = durationInMinutes
val tempData = PumpDbEntryTBR(absoluteRate, true, durationInMinutes, tbrType) val tempData = info.nightscout.androidaps.plugins.pump.common.sync.PumpDbEntryTBR(absoluteRate, true, durationInMinutes, tbrType)
pumpSyncStorage.addTemporaryBasalRateWithTempId(tempData, true, this) pumpSyncStorage.addTemporaryBasalRateWithTempId(tempData, true, this)
@ -956,10 +956,13 @@ class MedtronicPumpPlugin @Inject constructor(
val tbr = responseTask.result as TempBasalPair? val tbr = responseTask.result as TempBasalPair?
// we sometimes get rate returned even if TBR is no longer running // we sometimes get rate returned even if TBR is no longer running
if (tbr!!.durationMinutes == 0) { if (tbr != null) {
if (tbr.durationMinutes == 0) {
tbr.insulinRate = 0.0 tbr.insulinRate = 0.0
} }
tbr tbr
} else
null
} else { } else {
null null
} }
@ -992,7 +995,11 @@ class MedtronicPumpPlugin @Inject constructor(
val responseTask2 = rileyLinkMedtronicService.medtronicUIComm.executeCommand(MedtronicCommandType.CancelTBR) val responseTask2 = rileyLinkMedtronicService.medtronicUIComm.executeCommand(MedtronicCommandType.CancelTBR)
val response = responseTask2.result as Boolean? val response = responseTask2.result as Boolean?
finishAction("TBR") finishAction("TBR")
return if (response!!) { return if (response == null || !response) {
aapsLogger.info(LTag.PUMP, logPrefix + "cancelTempBasal - Cancel TBR failed.")
PumpEnactResult(injector).success(false).enacted(false) //
.comment(R.string.medtronic_cmd_cant_cancel_tbr)
} else {
aapsLogger.info(LTag.PUMP, logPrefix + "cancelTempBasal - Cancel TBR successful.") aapsLogger.info(LTag.PUMP, logPrefix + "cancelTempBasal - Cancel TBR successful.")
val runningTBR = medtronicPumpStatus.runningTBR val runningTBR = medtronicPumpStatus.runningTBR
@ -1022,19 +1029,13 @@ class MedtronicPumpPlugin @Inject constructor(
} }
} }
//pumpSyncStorage.addTemporaryBasalRateWithTempId(tempData, true, this)
PumpEnactResult(injector).success(true).enacted(true) // PumpEnactResult(injector).success(true).enacted(true) //
.isTempCancel(true) .isTempCancel(true)
} else {
aapsLogger.info(LTag.PUMP, logPrefix + "cancelTempBasal - Cancel TBR failed.")
PumpEnactResult(injector).success(response).enacted(response) //
.comment(R.string.medtronic_cmd_cant_cancel_tbr)
} }
} }
override fun manufacturer(): ManufacturerType { override fun manufacturer(): ManufacturerType {
return pumpDescription.pumpType.manufacturer!! return ManufacturerType.Medtronic
} }
override fun model(): PumpType { override fun model(): PumpType {

View file

@ -140,7 +140,7 @@ class MedtronicCommunicationManager // This empty constructor must be kept, oth
medtronicUtil.medtronicPumpModel = pumpModel!! medtronicUtil.medtronicPumpModel = pumpModel!!
medtronicUtil.isModelSet = true medtronicUtil.isModelSet = true
} }
aapsLogger.debug(LTag.PUMPCOMM, String.format(Locale.ENGLISH, "isDeviceReachable. PumpModel is %s - Valid: %b (rssi=%d)", pumpModel!!.name, valid, aapsLogger.debug(LTag.PUMPCOMM, String.format(Locale.ENGLISH, "isDeviceReachable. PumpModel is %s - Valid: %b (rssi=%d)", medtronicUtil.medtronicPumpModel, valid,
radioResponse.rssi)) radioResponse.rssi))
if (valid) { if (valid) {
if (state === PumpDeviceState.PumpUnreachable) if (state === PumpDeviceState.PumpUnreachable)
@ -313,7 +313,9 @@ class MedtronicCommunicationManager // This empty constructor must be kept, oth
aapsLogger.error(LTag.PUMPCOMM, String.format(Locale.ENGLISH, "Problem acknowledging frame response. (retry=%d)", retries)) aapsLogger.error(LTag.PUMPCOMM, String.format(Locale.ENGLISH, "Problem acknowledging frame response. (retry=%d)", retries))
} }
} }
if (nextMsg != null) currentResponse = GetHistoryPageCarelinkMessageBody(nextMsg.messageBody!!.txData) else { if (nextMsg != null)
currentResponse = GetHistoryPageCarelinkMessageBody(nextMsg.messageBody!!.txData)
else {
aapsLogger.error(LTag.PUMPCOMM, "We couldn't acknowledge frame from pump, aborting operation.") aapsLogger.error(LTag.PUMPCOMM, "We couldn't acknowledge frame from pump, aborting operation.")
} }
} }
@ -602,7 +604,7 @@ class MedtronicCommunicationManager // This empty constructor must be kept, oth
fun getTemporaryBasal(): TempBasalPair? { fun getTemporaryBasal(): TempBasalPair? {
return sendAndGetResponseWithCheck(MedtronicCommandType.ReadTemporaryBasal) { _, _, rawContent -> return sendAndGetResponseWithCheck(MedtronicCommandType.ReadTemporaryBasal) { _, _, rawContent ->
TempBasalPair(aapsLogger, rawContent!!) TempBasalPair(aapsLogger, rawContent)
} }
} }

View file

@ -117,7 +117,7 @@ class MedtronicPumpHistoryDecoder @Inject constructor(
if (decoded === RecordDecodeStatus.OK || decoded === RecordDecodeStatus.Ignored) { if (decoded === RecordDecodeStatus.OK || decoded === RecordDecodeStatus.Ignored) {
//Log.i(TAG, "#" + record + " " + decoded.getDescription() + " " + pe); //Log.i(TAG, "#" + record + " " + decoded.getDescription() + " " + pe);
} else { } else {
aapsLogger.warn(LTag.PUMPBTCOMM, "#" + record + " " + decoded!!.description + " " + pe) aapsLogger.warn(LTag.PUMPBTCOMM, "#" + record + " " + decoded.description + " " + pe)
} }
addToStatistics(pe, decoded, null) addToStatistics(pe, decoded, null)
record++ record++
@ -130,7 +130,7 @@ class MedtronicPumpHistoryDecoder @Inject constructor(
return outList return outList
} }
override fun decodeRecord(record: PumpHistoryEntry): RecordDecodeStatus? { override fun decodeRecord(record: PumpHistoryEntry): RecordDecodeStatus {
return try { return try {
decodeRecordInternal(record) decodeRecordInternal(record)
} catch (ex: Exception) { } catch (ex: Exception) {

View file

@ -39,7 +39,7 @@ class MedtronicUIPostprocessor @Inject constructor(
when (uiTask.commandType) { when (uiTask.commandType) {
MedtronicCommandType.SetBasalProfileSTD -> { MedtronicCommandType.SetBasalProfileSTD -> {
val response = uiTask.result as Boolean? val response = uiTask.result as Boolean?
if (response!!) { if (response != null && response) {
val basalProfile = uiTask.getParameter(0) as BasalProfile val basalProfile = uiTask.getParameter(0) as BasalProfile
aapsLogger.debug("D: basal profile returned after set: $basalProfile") aapsLogger.debug("D: basal profile returned after set: $basalProfile")

View file

@ -55,7 +55,7 @@ class MedtronicHistoryData @Inject constructor(
val medtronicPumpStatus: MedtronicPumpStatus, val medtronicPumpStatus: MedtronicPumpStatus,
val databaseHelper: DatabaseHelperInterface, val databaseHelper: DatabaseHelperInterface,
val pumpSync: PumpSync, val pumpSync: PumpSync,
val pumpSyncStorage: PumpSyncStorage val pumpSyncStorage: info.nightscout.androidaps.plugins.pump.common.sync.PumpSyncStorage
) { ) {
val allHistory: MutableList<PumpHistoryEntry> = mutableListOf() val allHistory: MutableList<PumpHistoryEntry> = mutableListOf()
@ -381,12 +381,12 @@ class MedtronicHistoryData @Inject constructor(
} }
} }
private fun processPrime(primeRecords: List<PumpHistoryEntry?>) { private fun processPrime(primeRecords: List<PumpHistoryEntry>) {
val maxAllowedTimeInPast = DateTimeUtil.getATDWithAddedMinutes(GregorianCalendar(), -30) val maxAllowedTimeInPast = DateTimeUtil.getATDWithAddedMinutes(GregorianCalendar(), -30)
var lastPrimeRecordTime = 0L var lastPrimeRecordTime = 0L
var lastPrimeRecord: PumpHistoryEntry? = null var lastPrimeRecord: PumpHistoryEntry? = null
for (primeRecord in primeRecords) { for (primeRecord in primeRecords) {
val fixedAmount = primeRecord!!.getDecodedDataEntry("FixedAmount") val fixedAmount = primeRecord.getDecodedDataEntry("FixedAmount")
if (fixedAmount != null && fixedAmount as Float == 0.0f) { if (fixedAmount != null && fixedAmount as Float == 0.0f) {
// non-fixed primes are used to prime the tubing // non-fixed primes are used to prime the tubing
// fixed primes are used to prime the cannula // fixed primes are used to prime the cannula
@ -456,7 +456,7 @@ class MedtronicHistoryData @Inject constructor(
pumpSync.createOrUpdateTotalDailyDose( pumpSync.createOrUpdateTotalDailyDose(
DateTimeUtil.toMillisFromATD(tdd.atechDateTime), DateTimeUtil.toMillisFromATD(tdd.atechDateTime),
totalsDTO.insulinBolus, totalsDTO.insulinBolus,
totalsDTO.insulinBasal!!, totalsDTO.insulinBasal,
totalsDTO.insulinTotal, totalsDTO.insulinTotal,
tdd.pumpId, tdd.pumpId,
medtronicPumpStatus.pumpType, medtronicPumpStatus.pumpType,
@ -559,7 +559,7 @@ class MedtronicHistoryData @Inject constructor(
if (bolus.containsDecodedData("Estimate")) { if (bolus.containsDecodedData("Estimate")) {
val bolusWizard = bolus.decodedData["Estimate"] as BolusWizardDTO val bolusWizard = bolus.decodedData["Estimate"] as BolusWizardDTO
pumpSyncStorage.addCarbs(PumpDbEntryCarbs( pumpSyncStorage.addCarbs(info.nightscout.androidaps.plugins.pump.common.sync.PumpDbEntryCarbs(
tryToGetByLocalTime(bolus.atechDateTime), tryToGetByLocalTime(bolus.atechDateTime),
bolusWizard.carbs.toDouble(), bolusWizard.carbs.toDouble(),
medtronicPumpStatus.pumpType, medtronicPumpStatus.pumpType,
@ -571,9 +571,9 @@ class MedtronicHistoryData @Inject constructor(
private fun processTBREntries(entryList: MutableList<PumpHistoryEntry>) { private fun processTBREntries(entryList: MutableList<PumpHistoryEntry>) {
Collections.reverse(entryList) Collections.reverse(entryList)
val tbr = entryList[0].getDecodedDataEntry("Object") as TempBasalPair? val tbr = entryList[0].getDecodedDataEntry("Object") as TempBasalPair
var readOldItem = false var readOldItem = false
if (tbr!!.isCancelTBR) { if (tbr.isCancelTBR) {
val oneMoreEntryFromHistory = getOneMoreEntryFromHistory(PumpHistoryEntryType.TempBasalCombined) val oneMoreEntryFromHistory = getOneMoreEntryFromHistory(PumpHistoryEntryType.TempBasalCombined)
if (oneMoreEntryFromHistory != null) { if (oneMoreEntryFromHistory != null) {
entryList.add(0, oneMoreEntryFromHistory) entryList.add(0, oneMoreEntryFromHistory)
@ -679,12 +679,12 @@ class MedtronicHistoryData @Inject constructor(
if (isTBRActive(tryToGetByLocalTime(tempBasalProcessDTO.atechDateTime), tempBasalProcessDTO.duration)) { if (isTBRActive(tryToGetByLocalTime(tempBasalProcessDTO.atechDateTime), tempBasalProcessDTO.duration)) {
if (medtronicPumpStatus.runningTBR == null) { if (medtronicPumpStatus.runningTBR == null) {
medtronicPumpStatus.runningTBR = PumpDbEntry(0L, medtronicPumpStatus.runningTBR = info.nightscout.androidaps.plugins.pump.common.sync.PumpDbEntry(0L,
tryToGetByLocalTime(tempBasalProcessDTO.atechDateTime), tryToGetByLocalTime(tempBasalProcessDTO.atechDateTime),
medtronicPumpStatus.pumpType, medtronicPumpStatus.pumpType,
medtronicPumpStatus.serialNumber, medtronicPumpStatus.serialNumber,
null, null,
PumpDbEntryTBR(tbrEntry.insulinRate, !tbrEntry.isPercent, tempBasalProcessDTO.duration, PumpSync.TemporaryBasalType.NORMAL), info.nightscout.androidaps.plugins.pump.common.sync.PumpDbEntryTBR(tbrEntry.insulinRate, !tbrEntry.isPercent, tempBasalProcessDTO.duration, PumpSync.TemporaryBasalType.NORMAL),
tempBasalProcessDTO.pumpId) tempBasalProcessDTO.pumpId)
} }
} }
@ -693,7 +693,7 @@ class MedtronicHistoryData @Inject constructor(
} // collection } // collection
} }
fun isTBRActive(dbEntry: PumpDbEntry): Boolean { fun isTBRActive(dbEntry: info.nightscout.androidaps.plugins.pump.common.sync.PumpDbEntry): Boolean {
return isTBRActive(dbEntry.date, dbEntry.tbrData!!.durationInMinutes) return isTBRActive(dbEntry.date, dbEntry.tbrData!!.durationInMinutes)
} }
@ -716,7 +716,7 @@ class MedtronicHistoryData @Inject constructor(
/** /**
* Looks at all boluses that have temporaryId and find one that is correct for us (if such entry exists) * Looks at all boluses that have temporaryId and find one that is correct for us (if such entry exists)
*/ */
private fun findDbEntry(treatment: PumpHistoryEntry, temporaryEntries: MutableList<PumpDbEntry>): PumpDbEntry? { private fun findDbEntry(treatment: PumpHistoryEntry, temporaryEntries: MutableList<info.nightscout.androidaps.plugins.pump.common.sync.PumpDbEntry>): info.nightscout.androidaps.plugins.pump.common.sync.PumpDbEntry? {
if (temporaryEntries.isEmpty()) { if (temporaryEntries.isEmpty()) {
return null return null
@ -728,7 +728,7 @@ class MedtronicHistoryData @Inject constructor(
this.pumpTime?.let { proposedTime += (it.timeDifference * 1000) } this.pumpTime?.let { proposedTime += (it.timeDifference * 1000) }
val proposedTimeDiff: LongArray = longArrayOf(proposedTime - (2 * 60 * 1000), proposedTime + (2L * 60L * 1000L)) val proposedTimeDiff: LongArray = longArrayOf(proposedTime - (2 * 60 * 1000), proposedTime + (2L * 60L * 1000L))
val tempEntriesList: MutableList<PumpDbEntry> = mutableListOf() val tempEntriesList: MutableList<info.nightscout.androidaps.plugins.pump.common.sync.PumpDbEntry> = mutableListOf()
for (temporaryEntry in temporaryEntries) { for (temporaryEntry in temporaryEntries) {
if (temporaryEntry.date > proposedTimeDiff[0] && temporaryEntry.date < proposedTimeDiff[1]) { if (temporaryEntry.date > proposedTimeDiff[0] && temporaryEntry.date < proposedTimeDiff[1]) {
@ -750,7 +750,7 @@ class MedtronicHistoryData @Inject constructor(
sec = 59 sec = 59
} }
val diff = sec * 1000 val diff = sec * 1000
val outList: MutableList<PumpDbEntry> = mutableListOf() val outList: MutableList<info.nightscout.androidaps.plugins.pump.common.sync.PumpDbEntry> = mutableListOf()
for (treatment1 in tempEntriesList) { for (treatment1 in tempEntriesList) {
if (treatment1.date > proposedTime - diff && treatment1.date < proposedTime + diff) { if (treatment1.date > proposedTime - diff && treatment1.date < proposedTime + diff) {
outList.add(treatment1) outList.add(treatment1)

View file

@ -36,18 +36,9 @@ class BolusDTO constructor(atechDateTime: Long,
@Expose var duration: Int = 0 @Expose var duration: Int = 0
) : PumpTimeStampedRecord(atechDateTime) { ) : PumpTimeStampedRecord(atechDateTime) {
// @Expose
// var requestedAmount: Double? = null
//
// @Expose
// var deliveredAmount: Double? = null
@Expose @Expose
var immediateAmount: Double? = null // when Multiwave this is used var immediateAmount: Double? = null // when Multiwave this is used
// @Expose
// var duration: Int? = null
@Expose @Expose
lateinit var bolusType: PumpBolusType lateinit var bolusType: PumpBolusType

View file

@ -36,7 +36,7 @@ class DailyTotalsDTO(var entry: PumpHistoryEntry) {
var insulinTotal = 0.0 var insulinTotal = 0.0
@Expose @Expose
var insulinBasal: Double? = 0.0 var insulinBasal: Double = 0.0
@Expose @Expose
var insulinBolus = 0.0 var insulinBolus = 0.0
@ -55,7 +55,7 @@ class DailyTotalsDTO(var entry: PumpHistoryEntry) {
private var bolusCountFood: Int? = null private var bolusCountFood: Int? = null
private var bolusCountCorr: Int? = null private var bolusCountCorr: Int? = null
private fun setDisplayable() { private fun setDisplayable() {
if (insulinBasal == null) { if (insulinBasal == 0.0) {
entry.displayableValue = "Total Insulin: " + StringUtil.getFormatedValueUS(insulinTotal, 2) entry.displayableValue = "Total Insulin: " + StringUtil.getFormatedValueUS(insulinTotal, 2)
} else { } else {
entry.displayableValue = ("Basal Insulin: " + StringUtil.getFormatedValueUS(insulinBasal, 2) entry.displayableValue = ("Basal Insulin: " + StringUtil.getFormatedValueUS(insulinBasal, 2)

View file

@ -157,8 +157,8 @@ enum class MedtronicCommandType {
} }
@JvmStatic @JvmStatic
fun getSettings(medtronicPumpModel: MedtronicDeviceType?): MedtronicCommandType { fun getSettings(medtronicPumpModel: MedtronicDeviceType): MedtronicCommandType {
return if (isSameDevice(medtronicPumpModel!!, MedtronicDeviceType.Medtronic_512_712)) return if (isSameDevice(medtronicPumpModel, MedtronicDeviceType.Medtronic_512_712))
Settings_512 Settings_512
else else
Settings Settings

View file

@ -13,7 +13,7 @@ enum class MedtronicStatusRefreshType(val refreshTime: Int,
PumpTime(60, MedtronicCommandType.GetRealTimeClock // PumpTime(60, MedtronicCommandType.GetRealTimeClock //
); );
fun getCommandType(medtronicDeviceType: MedtronicDeviceType?): MedtronicCommandType? { fun getCommandType(medtronicDeviceType: MedtronicDeviceType): MedtronicCommandType? {
return if (this == Configuration) { return if (this == Configuration) {
MedtronicCommandType.getSettings(medtronicDeviceType) MedtronicCommandType.getSettings(medtronicDeviceType)
} else } else

View file

@ -33,7 +33,7 @@ class MedtronicHistoryActivity : DaggerActivity() {
var filteredHistoryList: MutableList<PumpHistoryEntry> = ArrayList() var filteredHistoryList: MutableList<PumpHistoryEntry> = ArrayList()
var manualChange = false var manualChange = false
var typeListFull: List<TypeList>? = null lateinit var typeListFull: List<TypeList>
//private var _binding: MedtronicHistoryActivityBinding? = null //private var _binding: MedtronicHistoryActivityBinding? = null
@ -74,8 +74,8 @@ class MedtronicHistoryActivity : DaggerActivity() {
private fun setHistoryTypeSpinner() { private fun setHistoryTypeSpinner() {
manualChange = true manualChange = true
for (i in typeListFull!!.indices) { for (i in typeListFull.indices) {
if (typeListFull!![i].entryGroup === selectedGroup) { if (typeListFull[i].entryGroup === selectedGroup) {
historyTypeSpinner.setSelection(i) historyTypeSpinner.setSelection(i)
break break
} }
@ -119,15 +119,16 @@ class MedtronicHistoryActivity : DaggerActivity() {
}) })
} }
private fun getTypeList(list: List<PumpHistoryEntryGroup>?): List<TypeList> { private fun getTypeList(list: List<PumpHistoryEntryGroup>): List<TypeList> {
val typeList = ArrayList<TypeList>() val typeList = ArrayList<TypeList>()
for (pumpHistoryEntryGroup in list!!) { for (pumpHistoryEntryGroup in list) {
typeList.add(TypeList(pumpHistoryEntryGroup)) typeList.add(TypeList(pumpHistoryEntryGroup))
} }
return typeList return typeList
} }
class TypeList internal constructor(var entryGroup: PumpHistoryEntryGroup) { class TypeList internal constructor(var entryGroup: PumpHistoryEntryGroup) {
var name: String var name: String
override fun toString(): String { override fun toString(): String {
return name return name
@ -140,7 +141,6 @@ class MedtronicHistoryActivity : DaggerActivity() {
class RecyclerViewAdapter internal constructor(var historyList: List<PumpHistoryEntry>) : RecyclerView.Adapter<RecyclerViewAdapter.HistoryViewHolder>() { class RecyclerViewAdapter internal constructor(var historyList: List<PumpHistoryEntry>) : RecyclerView.Adapter<RecyclerViewAdapter.HistoryViewHolder>() {
fun setHistoryListInternal(historyList: List<PumpHistoryEntry>) { fun setHistoryListInternal(historyList: List<PumpHistoryEntry>) {
// this.historyList.clear(); // this.historyList.clear();
// this.historyList.addAll(historyList); // this.historyList.addAll(historyList);
@ -157,22 +157,17 @@ class MedtronicHistoryActivity : DaggerActivity() {
override fun onBindViewHolder(holder: HistoryViewHolder, position: Int) { override fun onBindViewHolder(holder: HistoryViewHolder, position: Int) {
val record = historyList[position] val record = historyList[position]
//if (record != null) {
holder.timeView.text = record.dateTimeString holder.timeView.text = record.dateTimeString
holder.typeView.text = record.entryType.description holder.typeView.text = record.entryType.description
holder.valueView.text = record.displayableValue holder.valueView.text = record.displayableValue
//}
} }
override fun getItemCount(): Int { override fun getItemCount(): Int {
return historyList.size return historyList.size
} }
override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
super.onAttachedToRecyclerView(recyclerView)
}
class HistoryViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { class HistoryViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var timeView: TextView var timeView: TextView
var typeView: TextView var typeView: TextView
var valueView: TextView var valueView: TextView
@ -188,6 +183,7 @@ class MedtronicHistoryActivity : DaggerActivity() {
} }
companion object { companion object {
var showingType: TypeList? = null var showingType: TypeList? = null
var selectedGroup = PumpHistoryEntryGroup.All var selectedGroup = PumpHistoryEntryGroup.All
} }

View file

@ -27,14 +27,14 @@ class MedtronicPumpStatus @Inject constructor(private val resourceHelper: Resour
private val sp: SP, private val sp: SP,
private val rxBus: RxBusWrapper, private val rxBus: RxBusWrapper,
private val rileyLinkUtil: RileyLinkUtil private val rileyLinkUtil: RileyLinkUtil
) : PumpStatus(PumpType.MEDTRONIC_522_722) { ) : info.nightscout.androidaps.plugins.pump.common.data.PumpStatus(PumpType.MEDTRONIC_522_722) {
var errorDescription: String? = null var errorDescription: String? = null
lateinit var serialNumber: String //? = null lateinit var serialNumber: String //? = null
var pumpFrequency: String? = null var pumpFrequency: String? = null
var maxBolus: Double? = null var maxBolus: Double? = null
var maxBasal: Double? = null var maxBasal: Double? = null
var runningTBR: PumpDbEntry? = null var runningTBR: info.nightscout.androidaps.plugins.pump.common.sync.PumpDbEntry? = null
// statuses // statuses
var pumpDeviceState = PumpDeviceState.NeverContacted var pumpDeviceState = PumpDeviceState.NeverContacted

1
pump-common/.gitignore vendored Normal file
View file

@ -0,0 +1 @@
/build

24
pump-common/build.gradle Normal file
View file

@ -0,0 +1,24 @@
apply plugin: 'com.android.library'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'
apply plugin: 'com.hiya.jacoco-android'
apply from: "${project.rootDir}/gradle/android_dependencies.gradle"
apply from: "${project.rootDir}/gradle/android_module_dependencies.gradle"
apply from: "${project.rootDir}/gradle/test_dependencies.gradle"
android {
defaultConfig {
versionCode 1
versionName "1.0"
}
}
dependencies {
implementation project(':core')
//implementation project(':database')
implementation('com.thoughtworks.xstream:xstream:1.4.7') {
exclude group: 'xmlpull', module: 'xmlpull'
}
}

View file

21
pump-common/proguard-rules.pro vendored Normal file
View file

@ -0,0 +1,21 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile

View file

@ -0,0 +1,7 @@
<manifest package="info.nightscout.androidaps.plugins.pump.common">
<application>
</application>
</manifest>

View file

@ -24,9 +24,6 @@ import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewB
import info.nightscout.androidaps.plugins.pump.common.data.PumpStatus import info.nightscout.androidaps.plugins.pump.common.data.PumpStatus
import info.nightscout.androidaps.plugins.pump.common.defs.PumpDriverState import info.nightscout.androidaps.plugins.pump.common.defs.PumpDriverState
import info.nightscout.androidaps.plugins.pump.common.defs.PumpType import info.nightscout.androidaps.plugins.pump.common.defs.PumpType
import info.nightscout.androidaps.plugins.pump.common.sync.PumpDbEntryCarbs
import info.nightscout.androidaps.plugins.pump.common.sync.PumpSyncEntriesCreator
import info.nightscout.androidaps.plugins.pump.common.sync.PumpSyncStorage
import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.DecimalFormatter.to0Decimal import info.nightscout.androidaps.utils.DecimalFormatter.to0Decimal
import info.nightscout.androidaps.utils.DecimalFormatter.to2Decimal import info.nightscout.androidaps.utils.DecimalFormatter.to2Decimal
@ -38,7 +35,6 @@ import io.reactivex.disposables.CompositeDisposable
import org.json.JSONException import org.json.JSONException
import org.json.JSONObject import org.json.JSONObject
/** /**
* Created by andy on 23.04.18. * Created by andy on 23.04.18.
*/ */
@ -58,8 +54,8 @@ abstract class PumpPluginAbstract protected constructor(
var dateUtil: DateUtil, var dateUtil: DateUtil,
var aapsSchedulers: AapsSchedulers, var aapsSchedulers: AapsSchedulers,
var pumpSync: PumpSync, var pumpSync: PumpSync,
var pumpSyncStorage: PumpSyncStorage var pumpSyncStorage: info.nightscout.androidaps.plugins.pump.common.sync.PumpSyncStorage
) : PumpPluginBase(pluginDescription!!, injector!!, aapsLogger, resourceHelper, commandQueue), Pump, Constraints, PumpSyncEntriesCreator { ) : PumpPluginBase(pluginDescription!!, injector!!, aapsLogger, resourceHelper, commandQueue), Pump, Constraints, info.nightscout.androidaps.plugins.pump.common.sync.PumpSyncEntriesCreator {
private val disposable = CompositeDisposable() private val disposable = CompositeDisposable()
@ -79,7 +75,6 @@ abstract class PumpPluginAbstract protected constructor(
pumpDescription.fillFor(value) pumpDescription.fillFor(value)
} }
protected var gson = GsonBuilder().excludeFieldsWithoutExposeAnnotation().create() protected var gson = GsonBuilder().excludeFieldsWithoutExposeAnnotation().create()
abstract fun initPumpStatusData() abstract fun initPumpStatusData()
@ -343,7 +338,7 @@ abstract class PumpPluginAbstract protected constructor(
detailedBolusInfo.timestamp = System.currentTimeMillis() detailedBolusInfo.timestamp = System.currentTimeMillis()
// no bolus required, carb only treatment // no bolus required, carb only treatment
pumpSyncStorage.addCarbs(PumpDbEntryCarbs(detailedBolusInfo, this)) pumpSyncStorage.addCarbs(info.nightscout.androidaps.plugins.pump.common.sync.PumpDbEntryCarbs(detailedBolusInfo, this))
val bolusingEvent = EventOverviewBolusProgress val bolusingEvent = EventOverviewBolusProgress
bolusingEvent.t = EventOverviewBolusProgress.Treatment(0.0, detailedBolusInfo.carbs.toInt(), detailedBolusInfo.bolusType === DetailedBolusInfo.BolusType.SMB) bolusingEvent.t = EventOverviewBolusProgress.Treatment(0.0, detailedBolusInfo.carbs.toInt(), detailedBolusInfo.bolusType === DetailedBolusInfo.BolusType.SMB)
@ -370,12 +365,11 @@ abstract class PumpPluginAbstract protected constructor(
return pumpType return pumpType
} }
override fun canHandleDST(): Boolean { override fun canHandleDST(): Boolean {
return false return false
} }
protected abstract fun deliverBolus(detailedBolusInfo: DetailedBolusInfo?): PumpEnactResult protected abstract fun deliverBolus(detailedBolusInfo: DetailedBolusInfo): PumpEnactResult
protected abstract fun triggerUIChange() protected abstract fun triggerUIChange()
@ -383,7 +377,6 @@ abstract class PumpPluginAbstract protected constructor(
return PumpEnactResult(injector).success(false).enacted(false).comment(resourceId) return PumpEnactResult(injector).success(false).enacted(false).comment(resourceId)
} }
init { init {
pumpDescription.fillFor(pumpType) pumpDescription.fillFor(pumpType)
this.pumpType = pumpType this.pumpType = pumpType

View file

@ -4,7 +4,6 @@ import info.nightscout.androidaps.data.DetailedBolusInfo
import info.nightscout.androidaps.interfaces.PumpSync import info.nightscout.androidaps.interfaces.PumpSync
import info.nightscout.androidaps.plugins.pump.common.defs.PumpType import info.nightscout.androidaps.plugins.pump.common.defs.PumpType
data class PumpDbEntry constructor(var temporaryId: Long, data class PumpDbEntry constructor(var temporaryId: Long,
var date: Long, var date: Long,
var pumpType: PumpType, var pumpType: PumpType,
@ -41,7 +40,6 @@ data class PumpDbEntry constructor(var temporaryId: Long,
} }
data class PumpDbEntryBolus(var insulin: Double, data class PumpDbEntryBolus(var insulin: Double,
var carbs: Double, var carbs: Double,
var bolusType: DetailedBolusInfo.BolusType) var bolusType: DetailedBolusInfo.BolusType)
@ -51,6 +49,7 @@ data class PumpDbEntryCarbs(var date: Long,
var pumpType: PumpType, var pumpType: PumpType,
var serialNumber: String, var serialNumber: String,
var pumpId: Long? = null) { var pumpId: Long? = null) {
constructor(detailedBolusInfo: DetailedBolusInfo, constructor(detailedBolusInfo: DetailedBolusInfo,
creator: PumpSyncEntriesCreator) : this(detailedBolusInfo.timestamp, creator: PumpSyncEntriesCreator) : this(detailedBolusInfo.timestamp,
detailedBolusInfo.carbs, detailedBolusInfo.carbs,

View file

@ -2,14 +2,12 @@ package info.nightscout.androidaps.plugins.pump.common.sync
import com.google.gson.Gson import com.google.gson.Gson
import com.google.gson.GsonBuilder import com.google.gson.GsonBuilder
import com.google.gson.reflect.TypeToken
import com.thoughtworks.xstream.XStream import com.thoughtworks.xstream.XStream
import info.nightscout.androidaps.data.DetailedBolusInfo import info.nightscout.androidaps.data.DetailedBolusInfo
import info.nightscout.androidaps.interfaces.PumpSync import info.nightscout.androidaps.interfaces.PumpSync
import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.utils.sharedPreferences.SP import info.nightscout.androidaps.utils.sharedPreferences.SP
import java.lang.reflect.Type
import java.util.* import java.util.*
import javax.inject.Inject import javax.inject.Inject
import javax.inject.Singleton import javax.inject.Singleton
@ -32,12 +30,10 @@ class PumpSyncStorage @Inject constructor(
var gson: Gson = GsonBuilder().create() var gson: Gson = GsonBuilder().create()
var xstream: XStream = XStream() var xstream: XStream = XStream()
init { init {
initStorage() initStorage()
} }
fun initStorage() { fun initStorage() {
if (storageInitialized) if (storageInitialized)
return return
@ -61,7 +57,6 @@ class PumpSyncStorage @Inject constructor(
} }
} }
fun saveStorage() { fun saveStorage() {
if (!isStorageEmpty()) { if (!isStorageEmpty()) {
sp.putString(pumpSyncStorageKey, xstream.toXML(pumpSyncStorage)) sp.putString(pumpSyncStorageKey, xstream.toXML(pumpSyncStorage))
@ -69,22 +64,18 @@ class PumpSyncStorage @Inject constructor(
} }
} }
fun isStorageEmpty(): Boolean { fun isStorageEmpty(): Boolean {
return pumpSyncStorage[BOLUS]!!.isEmpty() && pumpSyncStorage[TBR]!!.isEmpty() return pumpSyncStorage[BOLUS]!!.isEmpty() && pumpSyncStorage[TBR]!!.isEmpty()
} }
fun getBoluses(): MutableList<PumpDbEntry> { fun getBoluses(): MutableList<PumpDbEntry> {
return pumpSyncStorage[BOLUS]!!; return pumpSyncStorage[BOLUS]!!;
} }
fun getTBRs(): MutableList<PumpDbEntry> { fun getTBRs(): MutableList<PumpDbEntry> {
return pumpSyncStorage[TBR]!!; return pumpSyncStorage[TBR]!!;
} }
fun addBolusWithTempId(detailedBolusInfo: DetailedBolusInfo, writeToInternalHistory: Boolean, creator: PumpSyncEntriesCreator): Boolean { fun addBolusWithTempId(detailedBolusInfo: DetailedBolusInfo, writeToInternalHistory: Boolean, creator: PumpSyncEntriesCreator): Boolean {
val temporaryId = creator.generateTempId(detailedBolusInfo.timestamp) val temporaryId = creator.generateTempId(detailedBolusInfo.timestamp)
val result = pumpSync.addBolusWithTempId( val result = pumpSync.addBolusWithTempId(
@ -104,7 +95,7 @@ class PumpSyncStorage @Inject constructor(
} }
if (result && writeToInternalHistory) { if (result && writeToInternalHistory) {
var innerList: MutableList<PumpDbEntry> = pumpSyncStorage[BOLUS]!! val innerList: MutableList<PumpDbEntry> = pumpSyncStorage[BOLUS]!!
innerList.add(PumpDbEntry(temporaryId, detailedBolusInfo.timestamp, creator.model(), creator.serialNumber(), detailedBolusInfo)) innerList.add(PumpDbEntry(temporaryId, detailedBolusInfo.timestamp, creator.model(), creator.serialNumber(), detailedBolusInfo))
pumpSyncStorage[BOLUS] = innerList pumpSyncStorage[BOLUS] = innerList
@ -113,7 +104,6 @@ class PumpSyncStorage @Inject constructor(
return result return result
} }
fun addCarbs(carbsDto: PumpDbEntryCarbs) { fun addCarbs(carbsDto: PumpDbEntryCarbs) {
val result = pumpSync.syncCarbsWithTimestamp( val result = pumpSync.syncCarbsWithTimestamp(
carbsDto.date, carbsDto.date,
@ -126,7 +116,6 @@ class PumpSyncStorage @Inject constructor(
carbsDto.date, carbsDto.carbs, carbsDto.serialNumber, result)) carbsDto.date, carbsDto.carbs, carbsDto.serialNumber, result))
} }
fun addTemporaryBasalRateWithTempId(temporaryBasal: PumpDbEntryTBR, writeToInternalHistory: Boolean, creator: PumpSyncEntriesCreator): Boolean { fun addTemporaryBasalRateWithTempId(temporaryBasal: PumpDbEntryTBR, writeToInternalHistory: Boolean, creator: PumpSyncEntriesCreator): Boolean {
val timenow: Long = System.currentTimeMillis() val timenow: Long = System.currentTimeMillis()
val temporaryId = creator.generateTempId(timenow) val temporaryId = creator.generateTempId(timenow)
@ -142,7 +131,7 @@ class PumpSyncStorage @Inject constructor(
creator.serialNumber()) creator.serialNumber())
if (response && writeToInternalHistory) { if (response && writeToInternalHistory) {
var innerList: MutableList<PumpDbEntry> = pumpSyncStorage[TBR]!! val innerList: MutableList<PumpDbEntry> = pumpSyncStorage[TBR]!!
innerList.add(PumpDbEntry(temporaryId, timenow, creator.model(), creator.serialNumber(), null, temporaryBasal)) innerList.add(PumpDbEntry(temporaryId, timenow, creator.model(), creator.serialNumber(), null, temporaryBasal))
pumpSyncStorage[BOLUS] = innerList pumpSyncStorage[BOLUS] = innerList
@ -152,21 +141,18 @@ class PumpSyncStorage @Inject constructor(
return response; return response;
} }
fun removeBolusWithTemporaryId(temporaryId: Long) { fun removeBolusWithTemporaryId(temporaryId: Long) {
val bolusList = removeTemporaryId(temporaryId, pumpSyncStorage[BOLUS]!!) val bolusList = removeTemporaryId(temporaryId, pumpSyncStorage[BOLUS]!!)
pumpSyncStorage[BOLUS] = bolusList pumpSyncStorage[BOLUS] = bolusList
saveStorage() saveStorage()
} }
fun removeTemporaryBasalWithTemporaryId(temporaryId: Long) { fun removeTemporaryBasalWithTemporaryId(temporaryId: Long) {
val tbrList = removeTemporaryId(temporaryId, pumpSyncStorage[TBR]!!) val tbrList = removeTemporaryId(temporaryId, pumpSyncStorage[TBR]!!)
pumpSyncStorage[TBR] = tbrList pumpSyncStorage[TBR] = tbrList
saveStorage() saveStorage()
} }
private fun removeTemporaryId(temporaryId: Long, list: MutableList<PumpDbEntry>): MutableList<PumpDbEntry> { private fun removeTemporaryId(temporaryId: Long, list: MutableList<PumpDbEntry>): MutableList<PumpDbEntry> {
var dbEntry: PumpDbEntry? = null var dbEntry: PumpDbEntry? = null

View file

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

View file

@ -8,8 +8,10 @@ include ':combo'
include ':dana' include ':dana'
include ':danar' include ':danar'
include ':danars' include ':danars'
include ':pump-common'
include ':rileylink' include ':rileylink'
include ':medtronic' include ':medtronic'
include ':omnipod-common' include ':omnipod-common'
include ':omnipod-eros' include ':omnipod-eros'
include ':omnipod-dash' include ':omnipod-dash'