PumpSync interface, VirtualPump, remove pump driver dependency to database

This commit is contained in:
Milos Kozak 2021-03-29 00:31:40 +02:00
parent df1e2c53db
commit e3ac451f8d
60 changed files with 574 additions and 298 deletions

View file

@ -11,7 +11,7 @@ import dagger.android.AndroidInjector
import dagger.android.DaggerApplication
import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.database.entities.TherapyEvent
import info.nightscout.androidaps.database.transactions.InsertTherapyEventIfNewTransaction
import info.nightscout.androidaps.database.transactions.InsertIfNewByTimestampTherapyEventTransaction
import info.nightscout.androidaps.database.transactions.VersionChangeTransaction
import info.nightscout.androidaps.db.CompatDBHelper
import info.nightscout.androidaps.db.DatabaseHelper
@ -70,7 +70,7 @@ class MainApp : DaggerApplication() {
commitHash = null
}
disposable += repository.runTransaction(VersionChangeTransaction(BuildConfig.VERSION_NAME, BuildConfig.VERSION_CODE, gitRemote, commitHash)).subscribe()
disposable += repository.runTransaction(InsertTherapyEventIfNewTransaction(timestamp = dateUtil._now(), type = TherapyEvent.Type.NOTE, note = getString(info.nightscout.androidaps.core.R.string.androidaps_start).toString() + " - " + Build.MANUFACTURER + " " + Build.MODEL, glucoseUnit = TherapyEvent.GlucoseUnit.MGDL)).subscribe()
disposable += repository.runTransaction(InsertIfNewByTimestampTherapyEventTransaction(timestamp = dateUtil._now(), type = TherapyEvent.Type.NOTE, note = getString(info.nightscout.androidaps.core.R.string.androidaps_start).toString() + " - " + Build.MANUFACTURER + " " + Build.MODEL, glucoseUnit = TherapyEvent.GlucoseUnit.MGDL)).subscribe()
disposable += compatDBHelper.dbChangeDisposable()
registerActivityLifecycleCallbacks(activityMonitor)
JodaTimeAndroid.init(this)

View file

@ -20,6 +20,7 @@ import info.nightscout.androidaps.plugins.general.nsclient.DataSyncSelectorImple
import info.nightscout.androidaps.plugins.general.nsclient.UploadQueue
import info.nightscout.androidaps.plugins.general.smsCommunicator.SmsCommunicatorPlugin
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin
import info.nightscout.androidaps.plugins.pump.PumpSyncImplementation
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin
import info.nightscout.androidaps.queue.CommandQueue
import info.nightscout.androidaps.utils.androidNotification.NotificationHolder
@ -30,6 +31,7 @@ import info.nightscout.androidaps.utils.sharedPreferences.SP
import info.nightscout.androidaps.utils.storage.FileStorage
import info.nightscout.androidaps.utils.storage.Storage
import javax.inject.Singleton
@Suppress("unused")
@Module(includes = [
AppModule.AppBindings::class
])
@ -87,6 +89,7 @@ open class AppModule {
@Binds fun bindSmsCommunicatorInterface(smsCommunicatorPlugin: SmsCommunicatorPlugin): SmsCommunicatorInterface
@Binds fun bindUploadQueueAdminInterfaceToUploadQueue(uploadQueueAdminInterface: UploadQueueAdminInterface) : UploadQueueInterface
@Binds fun bindDataSyncSelector(dataSyncSelectorImplementation: DataSyncSelectorImplementation): DataSyncSelector
@Binds fun bindPumpSync(pumpSyncImplementation: PumpSyncImplementation): PumpSync
}
}

View file

@ -18,7 +18,7 @@ import info.nightscout.androidaps.database.entities.TherapyEvent
import info.nightscout.androidaps.database.entities.UserEntry.Action
import info.nightscout.androidaps.database.entities.UserEntry.Units
import info.nightscout.androidaps.database.entities.UserEntry.ValueWithUnit
import info.nightscout.androidaps.database.transactions.InsertTherapyEventIfNewTransaction
import info.nightscout.androidaps.database.transactions.InsertIfNewByTimestampTherapyEventTransaction
import info.nightscout.androidaps.databinding.DialogCareBinding
import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.logging.LTag
@ -222,7 +222,7 @@ class CareDialog : DialogFragmentWithDate() {
activity?.let { activity ->
OKDialog.showConfirmation(activity, resourceHelper.gs(event), HtmlHelper.fromHtml(Joiner.on("<br/>").join(actions)), {
disposable += repository.runTransactionForResult(InsertTherapyEventIfNewTransaction(therapyEvent))
disposable += repository.runTransactionForResult(InsertIfNewByTimestampTherapyEventTransaction(therapyEvent))
.subscribe(
{ result -> result.inserted.forEach { aapsLogger.debug(LTag.DATABASE, "Inserted therapy event $it") } },
{ aapsLogger.error(LTag.DATABASE, "Error while saving therapy event", it) }

View file

@ -14,7 +14,7 @@ import info.nightscout.androidaps.database.entities.TherapyEvent
import info.nightscout.androidaps.database.entities.UserEntry.Action
import info.nightscout.androidaps.database.entities.UserEntry.Units
import info.nightscout.androidaps.database.entities.UserEntry.ValueWithUnit
import info.nightscout.androidaps.database.transactions.InsertTherapyEventIfNewTransaction
import info.nightscout.androidaps.database.transactions.InsertIfNewByTimestampTherapyEventTransaction
import info.nightscout.androidaps.databinding.DialogFillBinding
import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.CommandQueueProvider
@ -140,7 +140,7 @@ class FillDialog : DialogFragmentWithDate() {
}
if (siteChange) {
uel.log(Action.CAREPORTAL, notes, ValueWithUnit(TherapyEvent.Type.CANNULA_CHANGE.text, Units.TherapyEvent))
disposable += repository.runTransactionForResult(InsertTherapyEventIfNewTransaction(
disposable += repository.runTransactionForResult(InsertIfNewByTimestampTherapyEventTransaction(
timestamp = eventTime,
type = TherapyEvent.Type.CANNULA_CHANGE,
note = notes,
@ -153,7 +153,7 @@ class FillDialog : DialogFragmentWithDate() {
if (insulinChange) {
// add a second for case of both checked
uel.log(Action.CAREPORTAL, notes, ValueWithUnit(TherapyEvent.Type.INSULIN_CHANGE.text, Units.TherapyEvent))
disposable += repository.runTransactionForResult(InsertTherapyEventIfNewTransaction(
disposable += repository.runTransactionForResult(InsertIfNewByTimestampTherapyEventTransaction(
timestamp = eventTime + 1000,
type = TherapyEvent.Type.INSULIN_CHANGE,
note = notes,

View file

@ -18,7 +18,7 @@ import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.database.entities.TherapyEvent
import info.nightscout.androidaps.database.transactions.InsertTherapyEventAnnouncementTransaction
import info.nightscout.androidaps.database.transactions.InsertTherapyEventIfNewTransaction
import info.nightscout.androidaps.database.transactions.InsertIfNewByTimestampTherapyEventTransaction
import info.nightscout.androidaps.events.EventAcceptOpenLoopChange
import info.nightscout.androidaps.events.EventAutosensCalculationFinished
import info.nightscout.androidaps.events.EventNewBG
@ -653,7 +653,7 @@ open class LoopPlugin @Inject constructor(
}
override fun createOfflineEvent(durationInMinutes: Int) {
disposable += repository.runTransactionForResult(InsertTherapyEventIfNewTransaction(
disposable += repository.runTransactionForResult(InsertIfNewByTimestampTherapyEventTransaction(
timestamp = dateUtil._now(),
type = TherapyEvent.Type.APS_OFFLINE,
duration = T.mins(durationInMinutes.toLong()).msecs(),

View file

@ -7,7 +7,7 @@ import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.R
import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.database.entities.Food
import info.nightscout.androidaps.database.transactions.SyncFoodTransaction
import info.nightscout.androidaps.database.transactions.SyncNsFoodTransaction
import info.nightscout.androidaps.interfaces.PluginBase
import info.nightscout.androidaps.interfaces.PluginDescription
import info.nightscout.androidaps.interfaces.PluginType
@ -18,7 +18,6 @@ import info.nightscout.androidaps.utils.JsonHelper
import info.nightscout.androidaps.utils.extensions.foodFromJson
import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP
import org.json.JSONArray
import org.json.JSONObject
import javax.inject.Inject
import javax.inject.Singleton
@ -75,7 +74,7 @@ class FoodPlugin @Inject constructor(
isValid = false
).also { it.interfaceIDs.nightscoutId = JsonHelper.safeGetString(jsonFood, "_id") }
repository.runTransactionForResult(SyncFoodTransaction(delFood))
repository.runTransactionForResult(SyncNsFoodTransaction(delFood))
.doOnError {
aapsLogger.error(LTag.DATABASE, "Error while removing food", it)
ret = Result.failure()
@ -89,7 +88,7 @@ class FoodPlugin @Inject constructor(
else -> {
val food = foodFromJson(jsonFood)
if (food != null) {
repository.runTransactionForResult(SyncFoodTransaction(food))
repository.runTransactionForResult(SyncNsFoodTransaction(food))
.doOnError {
aapsLogger.error(LTag.DATABASE, "Error while adding/updating food", it)
ret = Result.failure()

View file

@ -205,10 +205,10 @@ class DataSyncSelectorImplementation @Inject constructor(
nsClientPlugin.nsClientService?.dbRemove("food", tt.first.interfaceIDs.nightscoutId, DataSyncSelector.PairFood(tt.first, tt.second))
// existing without nsId = create new
tt.first.isValid && tt.first.interfaceIDs.nightscoutId == null ->
nsClientPlugin.nsClientService?.dbAdd("food", tt.first.toJson(profileFunction.getUnits()), DataSyncSelector.PairFood(tt.first, tt.second))
nsClientPlugin.nsClientService?.dbAdd("food", tt.first.toJson(), DataSyncSelector.PairFood(tt.first, tt.second))
// existing with nsId = update
tt.first.isValid && tt.first.interfaceIDs.nightscoutId != null ->
nsClientPlugin.nsClientService?.dbUpdate("food", tt.first.interfaceIDs.nightscoutId, tt.first.toJson(profileFunction.getUnits()), DataSyncSelector.PairFood(tt.first, tt.second))
nsClientPlugin.nsClientService?.dbUpdate("food", tt.first.interfaceIDs.nightscoutId, tt.first.toJson(), DataSyncSelector.PairFood(tt.first, tt.second))
}
return true
}

View file

@ -9,8 +9,8 @@ import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.database.entities.TherapyEvent
import info.nightscout.androidaps.database.entities.UserEntry
import info.nightscout.androidaps.database.entities.UserEntry.ValueWithUnit
import info.nightscout.androidaps.database.transactions.SyncTemporaryTargetTransaction
import info.nightscout.androidaps.database.transactions.SyncTherapyEventTransaction
import info.nightscout.androidaps.database.transactions.SyncNsTemporaryTargetTransaction
import info.nightscout.androidaps.database.transactions.SyncNsTherapyEventTransaction
import info.nightscout.androidaps.events.EventNsTreatment
import info.nightscout.androidaps.interfaces.ConfigInterface
import info.nightscout.androidaps.interfaces.DatabaseHelperInterface
@ -78,7 +78,7 @@ class NSClientAddUpdateWorker(
rxBus.send(EventNsTreatment(EventNsTreatment.ADD, json))
eventType == TherapyEvent.Type.TEMPORARY_TARGET.text ->
temporaryTargetFromJson(json)?.let { temporaryTarget ->
repository.runTransactionForResult(SyncTemporaryTargetTransaction(temporaryTarget))
repository.runTransactionForResult(SyncNsTemporaryTargetTransaction(temporaryTarget))
.doOnError {
aapsLogger.error(LTag.DATABASE, "Error while saving temporary target", it)
ret = Result.failure()
@ -123,7 +123,7 @@ class NSClientAddUpdateWorker(
eventType == TherapyEvent.Type.APS_OFFLINE.text ||
eventType == TherapyEvent.Type.PUMP_BATTERY_CHANGE.text ->
therapyEventFromJson(json)?.let { therapyEvent ->
repository.runTransactionForResult(SyncTherapyEventTransaction(therapyEvent))
repository.runTransactionForResult(SyncNsTherapyEventTransaction(therapyEvent))
.doOnError {
aapsLogger.error(LTag.DATABASE, "Error while saving therapy event", it)
ret = Result.failure()

View file

@ -6,7 +6,7 @@ import androidx.work.WorkerParameters
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.R
import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.database.transactions.SyncTherapyEventTransaction
import info.nightscout.androidaps.database.transactions.SyncNsTherapyEventTransaction
import info.nightscout.androidaps.interfaces.ConfigInterface
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
@ -40,7 +40,7 @@ class NSClientMbgWorker(
for (i in 0 until mbgArray.length()) {
val nsMbg = NSMbg(mbgArray.getJSONObject(i))
if (!nsMbg.isValid()) continue
repository.runTransactionForResult(SyncTherapyEventTransaction(therapyEventFromNsMbg(nsMbg)))
repository.runTransactionForResult(SyncNsTherapyEventTransaction(therapyEventFromNsMbg(nsMbg)))
.doOnError {
aapsLogger.error("Error while saving therapy event", it)
ret = Result.failure()

View file

@ -8,8 +8,8 @@ import info.nightscout.androidaps.R
import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.database.entities.UserEntry
import info.nightscout.androidaps.database.entities.UserEntry.ValueWithUnit
import info.nightscout.androidaps.database.transactions.SyncTemporaryTargetTransaction
import info.nightscout.androidaps.database.transactions.SyncTherapyEventTransaction
import info.nightscout.androidaps.database.transactions.SyncNsTemporaryTargetTransaction
import info.nightscout.androidaps.database.transactions.SyncNsTherapyEventTransaction
import info.nightscout.androidaps.events.EventNsTreatment
import info.nightscout.androidaps.events.EventNsTreatment.Companion.REMOVE
import info.nightscout.androidaps.interfaces.ConfigInterface
@ -59,7 +59,7 @@ class NSClientRemoveWorker(
// room Temporary target
val temporaryTarget = temporaryTargetFromNsIdForInvalidating(nsId)
repository.runTransactionForResult(SyncTemporaryTargetTransaction(temporaryTarget))
repository.runTransactionForResult(SyncNsTemporaryTargetTransaction(temporaryTarget))
.doOnError {
aapsLogger.error(LTag.DATABASE, "Error while removing temporary target", it)
ret = Result.failure()
@ -79,7 +79,7 @@ class NSClientRemoveWorker(
// room Therapy Event
val therapyEvent = therapyEventFromNsIdForInvalidating(nsId)
repository.runTransactionForResult(SyncTherapyEventTransaction(therapyEvent))
repository.runTransactionForResult(SyncNsTherapyEventTransaction(therapyEvent))
.doOnError {
aapsLogger.error(LTag.DATABASE, "Error while removing therapy event", it)
ret = Result.failure()

View file

@ -51,6 +51,7 @@ class VirtualPumpPlugin @Inject constructor(
private val profileFunction: ProfileFunction,
private val treatmentsPlugin: TreatmentsPlugin,
commandQueue: CommandQueueProvider,
private val pumpSync: PumpSync,
private val config: Config,
private val dateUtil: DateUtil
) : PumpPluginBase(PluginDescription()
@ -181,22 +182,21 @@ class VirtualPumpPlugin @Inject constructor(
override fun deliverTreatment(detailedBolusInfo: DetailedBolusInfo): PumpEnactResult {
val result = PumpEnactResult(injector)
result.success = true
result.bolusDelivered = detailedBolusInfo.insulin
result.carbsDelivered = detailedBolusInfo.carbs
result.enacted = result.bolusDelivered > 0 || result.carbsDelivered > 0
result.comment = resourceHelper.gs(R.string.virtualpump_resultok)
.success(true)
.bolusDelivered(detailedBolusInfo.insulin)
.carbsDelivered(detailedBolusInfo.carbs)
.enacted(detailedBolusInfo.insulin > 0 || detailedBolusInfo.carbs > 0)
.comment(resourceHelper.gs(R.string.virtualpump_resultok))
val bolusingEvent = EventOverviewBolusProgress
var delivering = 0.0
while (delivering < detailedBolusInfo.insulin) {
SystemClock.sleep(200)
val bolusingEvent = EventOverviewBolusProgress
bolusingEvent.status = resourceHelper.gs(R.string.bolusdelivering, delivering)
bolusingEvent.percent = min((delivering / detailedBolusInfo.insulin * 100).toInt(), 100)
rxBus.send(bolusingEvent)
delivering += 0.1
}
SystemClock.sleep(200)
val bolusingEvent = EventOverviewBolusProgress
bolusingEvent.status = resourceHelper.gs(R.string.bolusdelivered, detailedBolusInfo.insulin)
bolusingEvent.percent = 100
rxBus.send(bolusingEvent)
@ -204,7 +204,10 @@ class VirtualPumpPlugin @Inject constructor(
aapsLogger.debug(LTag.PUMP, "Delivering treatment insulin: " + detailedBolusInfo.insulin + "U carbs: " + detailedBolusInfo.carbs + "g " + result)
rxBus.send(EventVirtualPumpUpdateGui())
lastDataTime = System.currentTimeMillis()
treatmentsPlugin.addToHistoryTreatment(detailedBolusInfo, false)
pumpSync.syncBolusWithPumpId(dateUtil._now(), detailedBolusInfo.insulin, detailedBolusInfo.bolusType, dateUtil._now(), pumpType
?: PumpType.GENERIC_AAPS, serialNumber())
pumpSync.syncCarbsWithTimestamp(dateUtil._now(), detailedBolusInfo.carbs, dateUtil._now(), pumpType
?: PumpType.GENERIC_AAPS, serialNumber())
return result
}

View file

@ -9,7 +9,7 @@ import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.database.entities.GlucoseValue
import info.nightscout.androidaps.database.entities.TherapyEvent
import info.nightscout.androidaps.database.transactions.CgmSourceTransaction
import info.nightscout.androidaps.database.transactions.InsertTherapyEventIfNewTransaction
import info.nightscout.androidaps.database.transactions.InsertIfNewByTimestampTherapyEventTransaction
import info.nightscout.androidaps.interfaces.BgSourceInterface
import info.nightscout.androidaps.interfaces.PluginBase
import info.nightscout.androidaps.interfaces.PluginDescription
@ -131,7 +131,7 @@ class EversensePlugin @Inject constructor(
aapsLogger.debug(LTag.BGSOURCE, "calibrationTimestamps" + Arrays.toString(calibrationTimestamps))
aapsLogger.debug(LTag.BGSOURCE, "calibrationRecordNumbers" + Arrays.toString(calibrationRecordNumbers))
for (i in calibrationGlucoseLevels.indices) {
repository.runTransactionForResult(InsertTherapyEventIfNewTransaction(
repository.runTransactionForResult(InsertIfNewByTimestampTherapyEventTransaction(
timestamp = calibrationTimestamps[i],
type = TherapyEvent.Type.FINGER_STICK_BG_VALUE,
glucose = calibrationGlucoseLevels[i].toDouble(),

View file

@ -24,7 +24,6 @@ import info.nightscout.androidaps.events.EventAutosensCalculationFinished
import info.nightscout.androidaps.events.EventTreatmentChange
import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.interfaces.UploadQueueInterface
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.logging.UserEntryLogger
@ -57,8 +56,6 @@ class TreatmentsBolusCarbsFragment : DaggerFragment() {
@Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var fabricPrivacy: FabricPrivacy
@Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var nsUpload: NSUpload
@Inject lateinit var uploadQueue: UploadQueueInterface
@Inject lateinit var dateUtil: DateUtil
@Inject lateinit var buildHelper: BuildHelper
@Inject lateinit var aapsSchedulers: AapsSchedulers
@ -120,13 +117,10 @@ class TreatmentsBolusCarbsFragment : DaggerFragment() {
.subscribe { list ->
list.forEach { bolus ->
disposable += repository.runTransactionForResult(InvalidateBolusTransaction(bolus.id))
.subscribe({
val id = bolus.interfaceIDs.nightscoutId
if (NSUpload.isIdValid(id)) nsUpload.removeCareportalEntryFromNS(id)
else uploadQueue.removeByMongoId("dbAdd", bolus.timestamp.toString())
}, {
aapsLogger.error(LTag.DATABASE, "Error while invalidating bolus", it)
})
.subscribe(
{ result -> result.invalidated.forEach { aapsLogger.debug(LTag.DATABASE, "Invalidated bolus $it") } },
{ aapsLogger.error(LTag.DATABASE, "Error while invalidating bolus", it) }
)
}
}
repository
@ -135,13 +129,10 @@ class TreatmentsBolusCarbsFragment : DaggerFragment() {
.subscribe { list ->
list.forEach { carb ->
disposable += repository.runTransactionForResult(InvalidateCarbsTransaction(carb.id))
.subscribe({
val id = carb.interfaceIDs.nightscoutId
if (NSUpload.isIdValid(id)) nsUpload.removeCareportalEntryFromNS(id)
else uploadQueue.removeByMongoId("dbAdd", carb.timestamp.toString())
}, {
aapsLogger.error(LTag.DATABASE, "Error while invalidating carbs", it)
})
.subscribe(
{ result -> result.invalidated.forEach { aapsLogger.debug(LTag.DATABASE, "Invalidated carbs $it") } },
{ aapsLogger.error(LTag.DATABASE, "Error while invalidating carbs", it) }
)
}
}
repository
@ -150,13 +141,10 @@ class TreatmentsBolusCarbsFragment : DaggerFragment() {
.subscribe { list ->
list.forEach { bolusCalc ->
disposable += repository.runTransactionForResult(InvalidateBolusCalculatorResultTransaction(bolusCalc.id))
.subscribe({
val id = bolusCalc.interfaceIDs.nightscoutId
if (NSUpload.isIdValid(id)) nsUpload.removeCareportalEntryFromNS(id)
else uploadQueue.removeByMongoId("dbAdd", bolusCalc.timestamp.toString())
}, {
aapsLogger.error(LTag.DATABASE, "Error while invalidating carbs", it)
})
.subscribe(
{ result -> result.invalidated.forEach { aapsLogger.debug(LTag.DATABASE, "Invalidated bolusCalculatorResult $it") } },
{ aapsLogger.error(LTag.DATABASE, "Error while invalidating bolusCalculatorResult", it) }
)
}
}
binding.deleteFutureTreatments.visibility = View.GONE
@ -350,13 +338,10 @@ class TreatmentsBolusCarbsFragment : DaggerFragment() {
// ValueWithUnit(mealLinkLoaded.carbs.toInt(), Units.G)
)
disposable += repository.runTransactionForResult(InvalidateBolusTransaction(bolus.id))
.subscribe({
val id = bolus.interfaceIDs.nightscoutId
if (NSUpload.isIdValid(id)) nsUpload.removeCareportalEntryFromNS(id)
else uploadQueue.removeByMongoId("dbAdd", bolus.timestamp.toString())
}, {
aapsLogger.error(LTag.DATABASE, "Error while invalidating bolus", it)
})
.subscribe(
{ result -> result.invalidated.forEach { aapsLogger.debug(LTag.DATABASE, "Invalidated bolus $it") } },
{ aapsLogger.error(LTag.DATABASE, "Error while invalidating bolus", it) }
)
})
}
}
@ -374,13 +359,10 @@ class TreatmentsBolusCarbsFragment : DaggerFragment() {
ValueWithUnit(carb.amount, Units.G)
)
disposable += repository.runTransactionForResult(InvalidateCarbsTransaction(carb.id))
.subscribe({
val id = carb.interfaceIDs.nightscoutId
if (NSUpload.isIdValid(id)) nsUpload.removeCareportalEntryFromNS(id)
else uploadQueue.removeByMongoId("dbAdd", carb.timestamp.toString())
}, {
aapsLogger.error(LTag.DATABASE, "Error while invalidating carbs", it)
})
.subscribe(
{ result -> result.invalidated.forEach { aapsLogger.debug(LTag.DATABASE, "Invalidated carbs $it") } },
{ aapsLogger.error(LTag.DATABASE, "Error while invalidating carbs", it) }
)
})
}
}

View file

@ -11,18 +11,18 @@ import dagger.android.support.DaggerFragment
import info.nightscout.androidaps.R
import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.database.entities.TherapyEvent
import info.nightscout.androidaps.database.entities.UserEntry.Action
import info.nightscout.androidaps.database.entities.UserEntry.Units
import info.nightscout.androidaps.database.entities.UserEntry.ValueWithUnit
import info.nightscout.androidaps.database.transactions.InvalidateAAPSStartedTherapyEventTransaction
import info.nightscout.androidaps.database.transactions.InvalidateTherapyEventTransaction
import info.nightscout.androidaps.database.entities.UserEntry.*
import info.nightscout.androidaps.databinding.TreatmentsCareportalFragmentBinding
import info.nightscout.androidaps.databinding.TreatmentsCareportalItemBinding
import info.nightscout.androidaps.events.EventTherapyEventChange
import info.nightscout.androidaps.interfaces.UploadQueueInterface
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.logging.UserEntryLogger
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload
import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientRestart
import info.nightscout.androidaps.plugins.treatments.events.EventTreatmentUpdateGui
import info.nightscout.androidaps.plugins.treatments.fragments.TreatmentsCareportalFragment.RecyclerViewAdapter.TherapyEventsViewHolder
@ -51,8 +51,6 @@ class TreatmentsCareportalFragment : DaggerFragment() {
@Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var fabricPrivacy: FabricPrivacy
@Inject lateinit var translator: Translator
@Inject lateinit var nsUpload: NSUpload
@Inject lateinit var uploadQueue: UploadQueueInterface
@Inject lateinit var dateUtil: DateUtil
@Inject lateinit var buildHelper: BuildHelper
@Inject lateinit var aapsSchedulers: AapsSchedulers
@ -95,18 +93,11 @@ class TreatmentsCareportalFragment : DaggerFragment() {
activity?.let { activity ->
OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.careportal), resourceHelper.gs(R.string.careportal_removestartedevents), Runnable {
uel.log(Action.RESTART_EVENTS_REMOVED)
// val events = databaseHelper.getCareportalEvents(false)
repository.runTransactionForResult(InvalidateAAPSStartedTherapyEventTransaction())
.subscribe({ result ->
result.invalidated.forEach { event ->
if (NSUpload.isIdValid(event.interfaceIDs.nightscoutId))
nsUpload.removeCareportalEntryFromNS(event.interfaceIDs.nightscoutId)
else
uploadQueue.removeByMongoId("dbAdd", event.timestamp.toString())
}
}, {
aapsLogger.error(LTag.DATABASE, "Error while invalidating therapy event", it)
})
repository.runTransactionForResult(InvalidateAAPSStartedTherapyEventTransaction(resourceHelper.gs(R.string.androidaps_start)))
.subscribe(
{ result -> result.invalidated.forEach { aapsLogger.debug(LTag.DATABASE, "Invalidated therapy event $it") } },
{ aapsLogger.error(LTag.DATABASE, "Error while invalidating therapy event", it) }
)
}, null)
}
}
@ -199,13 +190,10 @@ class TreatmentsCareportalFragment : DaggerFragment() {
OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.removerecord), text, Runnable {
uel.log(Action.CAREPORTAL_REMOVED, therapyEvent.note, ValueWithUnit(therapyEvent.timestamp, Units.Timestamp), ValueWithUnit(therapyEvent.type.text, Units.TherapyEvent))
disposable += repository.runTransactionForResult(InvalidateTherapyEventTransaction(therapyEvent.id))
.subscribe({
val id = therapyEvent.interfaceIDs.nightscoutId
if (NSUpload.isIdValid(id)) nsUpload.removeCareportalEntryFromNS(id)
else uploadQueue.removeByMongoId("dbAdd", therapyEvent.timestamp.toString())
}, {
aapsLogger.error(LTag.DATABASE, "Error while invalidating therapy event", it)
})
.subscribe(
{ result -> result.invalidated.forEach { aapsLogger.debug(LTag.DATABASE, "Invalidated therapy event $it") } },
{ aapsLogger.error(LTag.DATABASE, "Error while invalidating therapy event", it) }
)
}, null)
}
}

View file

@ -17,5 +17,4 @@ android {
dependencies {
implementation project(':core')
implementation project(':database')
}

View file

@ -72,7 +72,11 @@ class DetailedBolusInfo {
MEAL_BOLUS,
BOLUS_WIZARD,
CORRECTION_BOLUS,
CARBS_CORRECTION;
CARBS_CORRECTION,
CANNULA_CHANGE,
INSULIN_CHANGE,
PUMP_BATTERY_CHANGE,
NOTE;
fun toDBbEventType(): TherapyEvent.Type =
when (this) {
@ -80,6 +84,10 @@ class DetailedBolusInfo {
BOLUS_WIZARD -> TherapyEvent.Type.BOLUS_WIZARD
CORRECTION_BOLUS -> TherapyEvent.Type.CORRECTION_BOLUS
CARBS_CORRECTION -> TherapyEvent.Type.CARBS_CORRECTION
CANNULA_CHANGE -> TherapyEvent.Type.CANNULA_CHANGE
INSULIN_CHANGE -> TherapyEvent.Type.INSULIN_CHANGE
PUMP_BATTERY_CHANGE -> TherapyEvent.Type.PUMP_BATTERY_CHANGE
NOTE -> TherapyEvent.Type.NOTE
}
}

View file

@ -0,0 +1,79 @@
package info.nightscout.androidaps.interfaces
import info.nightscout.androidaps.data.DetailedBolusInfo
import info.nightscout.androidaps.plugins.pump.common.defs.PumpType
interface PumpSync {
fun addBolusWithTempId(timestamp: Long, amount: Double, driverId: Long, pumpType: PumpType, pumpSerial: String)
fun syncBolusWithTempId(timestamp: Long, amount: Double, driverId: Long, pumpId: Long?, pumpType: PumpType, pumpSerial: String)
/**
* Synchronization of boluses
*
* Search for combination of pumpId, PumpType, pumpSerial
*
* If db record doesn't exist, new record is created.
* If exists, data is updated
* isValid field is preserved
*
* @param timestamp timestamp of event from pump history
* @param amount amount of insulin
* @param type type of bolus (NORMAL, SMB, PRIME). Default is NORMAL
* @param pumpId pump id from history
* @param pumpType pump type like PumpType.ACCU_CHEK_COMBO
* @param pumpSerial pump serial number
**/
fun syncBolusWithPumpId(timestamp: Long, amount: Double, type: DetailedBolusInfo.BolusType = DetailedBolusInfo.BolusType.NORMAL, pumpId: Long, pumpType: PumpType, pumpSerial: String)
/**
* Synchronization of carbs
*
* Assuming there will be no clash on timestamp from different pumps or UI
* only timestamp is compared
*
* If db record doesn't exist, new record is created.
* If exists, data is ignored
*
* @param timestamp timestamp of event from pump history
* @param amount amount of carbs
* @param pumpId pump id from history if coming form pump history
* @param pumpType pump type like PumpType.ACCU_CHEK_COMBO
* @param pumpSerial pump serial number
**/
fun syncCarbsWithTimestamp(timestamp: Long, amount: Double, pumpId: Long?, pumpType: PumpType, pumpSerial: String)
/**
* Synchronization of events like CANNULA_CHANGE
*
* Assuming there will be no clash on timestamp from different pumps
* only timestamp and type is compared
*
* If db record doesn't exist, new record is created.
* If exists, data is ignored
*
* @param timestamp timestamp of event from pump history
* @param type type like CANNULA_CHANGE, INSULIN_CHANGE
* @param note note
* @param pumpId pump id from history if available
* @param pumpType pump type like PumpType.ACCU_CHEK_COMBO
* @param pumpSerial pump serial number
**/
fun insertTherapyEventIfNewWithTimestamp(timestamp: Long, type: DetailedBolusInfo.EventType, note: String? = null, pumpId: Long? = null, pumpType: PumpType, pumpSerial: String)
/**
* Create an announcement
*
* It's common TherapyEvent NOTE
* Event is sent to NS as an announcement
*
* Common use is report failures like occlusion, empty reservoir etc
*
* Created with now() as a timestamp
*
* @param error error message
* @param pumpId pump id from history if available
* @param pumpType pump type like PumpType.ACCU_CHEK_COMBO
* @param pumpSerial pump serial number
**/
fun insertAnnouncement(error: String, pumpId: Long? = null, pumpType: PumpType, pumpSerial: String)
}

View file

@ -0,0 +1,102 @@
package info.nightscout.androidaps.plugins.pump
import info.nightscout.androidaps.data.DetailedBolusInfo
import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.database.embedments.InterfaceIDs
import info.nightscout.androidaps.database.entities.Bolus
import info.nightscout.androidaps.database.entities.Carbs
import info.nightscout.androidaps.database.entities.TherapyEvent
import info.nightscout.androidaps.database.transactions.InsertIfNewByTimestampCarbsTransaction
import info.nightscout.androidaps.database.transactions.InsertIfNewByTimestampTherapyEventTransaction
import info.nightscout.androidaps.database.transactions.InsertTherapyEventAnnouncementTransaction
import info.nightscout.androidaps.database.transactions.SyncPumpBolusTransaction
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 io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.plusAssign
import javax.inject.Inject
class PumpSyncImplementation @Inject constructor(
private val aapsLogger: AAPSLogger,
private val repository: AppRepository
) : PumpSync {
private val disposable = CompositeDisposable()
override fun addBolusWithTempId(timestamp: Long, amount: Double, driverId: Long, pumpType: PumpType, pumpSerial: String) {
TODO("Not yet implemented")
}
override fun syncBolusWithTempId(timestamp: Long, amount: Double, driverId: Long, pumpId: Long?, pumpType: PumpType, pumpSerial: String) {
TODO("Not yet implemented")
}
override fun syncBolusWithPumpId(timestamp: Long, amount: Double, type: DetailedBolusInfo.BolusType, pumpId: Long, pumpType: PumpType, pumpSerial: String) {
val bolus = Bolus(
timestamp = timestamp,
amount = amount,
type = type.toDBbBolusType(),
interfaceIDs_backing = InterfaceIDs(
pumpId = pumpId,
pumpType = pumpType.toDbPumpType(),
pumpSerial = pumpSerial
),
isBasalInsulin = false
)
disposable += repository.runTransactionForResult(SyncPumpBolusTransaction(bolus))
.subscribe(
{ result ->
result.inserted.forEach { aapsLogger.debug(LTag.DATABASE, "Inserted carbs $it") }
result.updated.forEach { aapsLogger.debug(LTag.DATABASE, "Updated carbs $it") }
},
{ aapsLogger.error(LTag.DATABASE, "Error while saving carbs", it) }
)
}
override fun syncCarbsWithTimestamp(timestamp: Long, amount: Double, pumpId: Long?, pumpType: PumpType, pumpSerial: String) {
val carbs = Carbs(
timestamp = timestamp,
amount = amount,
duration = 0,
interfaceIDs_backing = InterfaceIDs(
pumpId = pumpId,
pumpType = pumpType.toDbPumpType(),
pumpSerial = pumpSerial)
)
disposable += repository.runTransactionForResult(InsertIfNewByTimestampCarbsTransaction(carbs))
.subscribe(
{ result -> result.inserted.forEach { aapsLogger.debug(LTag.DATABASE, "Inserted carbs $it") } },
{ aapsLogger.error(LTag.DATABASE, "Error while saving carbs", it) }
)
}
override fun insertTherapyEventIfNewWithTimestamp(timestamp: Long, type: DetailedBolusInfo.EventType, note: String?, pumpId: Long?, pumpType: PumpType, pumpSerial: String) {
val therapyEvent = TherapyEvent(
timestamp = timestamp,
type = type.toDBbEventType(),
duration = 0,
note = null,
enteredBy = "AndroidAPS",
glucose = null,
glucoseType = null,
glucoseUnit = TherapyEvent.GlucoseUnit.MGDL,
interfaceIDs_backing = InterfaceIDs(
pumpId = pumpId,
pumpType = pumpType.toDbPumpType(),
pumpSerial = pumpSerial)
)
disposable += repository.runTransactionForResult(InsertIfNewByTimestampTherapyEventTransaction(therapyEvent))
.subscribe(
{ result -> result.inserted.forEach { aapsLogger.debug(LTag.DATABASE, "Inserted therapy event $it") } },
{ aapsLogger.error(LTag.DATABASE, "Error while saving therapy event", it) }
)
}
override fun insertAnnouncement(error: String, pumpId: Long?, pumpType: PumpType, pumpSerial: String) {
disposable += repository.runTransaction(InsertTherapyEventAnnouncementTransaction(error, pumpId, pumpType.toDbPumpType(), pumpSerial))
.subscribe()
}
}

View file

@ -1,6 +1,7 @@
package info.nightscout.androidaps.plugins.pump.common.defs
import info.nightscout.androidaps.core.R
import info.nightscout.androidaps.database.embedments.InterfaceIDs
import info.nightscout.androidaps.plugins.common.ManufacturerType
import info.nightscout.androidaps.plugins.pump.common.data.DoseSettings
import info.nightscout.androidaps.utils.Round
@ -160,6 +161,8 @@ enum class PumpType {
baseBasalStep = 0.01,
baseBasalSpecialSteps = null,
pumpCapability = PumpCapability.DanaWithHistoryCapabilities),
DANA_RS_KOREAN(description = "DanaRSKorean", model = "DanaRSKorean", parent = DANA_RS),
DANA_I(description = "DanaI", model = "DanaI", parent = DANA_RS),
DANA_RV2(description = "DanaRv2", model = "DanaRv2", parent = DANA_RS),
OMNIPOD_EROS(description = "Omnipod Eros",
manufacturer = ManufacturerType.Insulet,
@ -275,6 +278,7 @@ enum class PumpType {
tbrSettings = DoseSettings(1.0, 15, 24 * 60, 0.0, 500.0),
extendedBolusSettings = DoseSettings(0.1, 15, 12 * 60, 0.1),
pumpCapability = PumpCapability.MDI),
// Not real pump. Used for User as a source
USER(description = "USER",
manufacturer = ManufacturerType.AndroidAPS,
@ -408,4 +412,38 @@ enum class PumpType {
return Round.roundTo(min(basalAmount, tSettings.maxDose), baseBasalSpecialSteps?.getStepSizeForAmount(basalAmount)
?: baseBasalStep)
}
fun toDbPumpType(): InterfaceIDs.PumpType =
when (this) {
GENERIC_AAPS -> InterfaceIDs.PumpType.GENERIC_AAPS
CELLNOVO -> InterfaceIDs.PumpType.CELLNOVO
ACCU_CHEK_COMBO -> InterfaceIDs.PumpType.ACCU_CHEK_COMBO
ACCU_CHEK_SPIRIT -> InterfaceIDs.PumpType.ACCU_CHEK_SPIRIT
ACCU_CHEK_INSIGHT -> InterfaceIDs.PumpType.ACCU_CHEK_INSIGHT
ACCU_CHEK_INSIGHT_BLUETOOTH -> InterfaceIDs.PumpType.ACCU_CHEK_INSIGHT_BLUETOOTH
ACCU_CHEK_SOLO -> InterfaceIDs.PumpType.ACCU_CHEK_SOLO
ANIMAS_VIBE -> InterfaceIDs.PumpType.ANIMAS_VIBE
ANIMAS_PING -> InterfaceIDs.PumpType.ANIMAS_PING
DANA_R -> InterfaceIDs.PumpType.DANA_R
DANA_R_KOREAN -> InterfaceIDs.PumpType.DANA_R_KOREAN
DANA_RS -> InterfaceIDs.PumpType.DANA_RS
DANA_RS_KOREAN -> InterfaceIDs.PumpType.DANA_RS_KOREAN
DANA_RV2 -> InterfaceIDs.PumpType.DANA_RV2
DANA_I -> InterfaceIDs.PumpType.DANA_I
OMNIPOD_EROS -> InterfaceIDs.PumpType.OMNIPOD_EROS
OMNIPOD_DASH -> InterfaceIDs.PumpType.OMNIPOD_DASH
MEDTRONIC_512_712 -> InterfaceIDs.PumpType.MEDTRONIC_512_517
MEDTRONIC_515_715 -> InterfaceIDs.PumpType.MEDTRONIC_515_715
MEDTRONIC_522_722 -> InterfaceIDs.PumpType.MEDTRONIC_522_722
MEDTRONIC_523_723_REVEL -> InterfaceIDs.PumpType.MEDTRONIC_523_723_REVEL
MEDTRONIC_554_754_VEO -> InterfaceIDs.PumpType.MEDTRONIC_554_754_VEO
MEDTRONIC_640G -> InterfaceIDs.PumpType.MEDTRONIC_640G
TANDEM_T_SLIM -> InterfaceIDs.PumpType.TANDEM_T_SLIM
TANDEM_T_SLIM_G4 -> InterfaceIDs.PumpType.TANDEM_T_SLIM_G4
TANDEM_T_FLEX -> InterfaceIDs.PumpType.TANDEM_T_FLEX
TANDEM_T_SLIM_X2 -> InterfaceIDs.PumpType.TANDEM_T_SLIM_X2
YPSOPUMP -> InterfaceIDs.PumpType.YPSOPUMP
MDI -> InterfaceIDs.PumpType.MDI
USER -> InterfaceIDs.PumpType.USER
}
}

View file

@ -2,11 +2,9 @@ package info.nightscout.androidaps.utils.extensions
import com.google.gson.Gson
import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.data.DetailedBolusInfo
import info.nightscout.androidaps.database.entities.BolusCalculatorResult
import info.nightscout.androidaps.database.entities.TherapyEvent
import info.nightscout.androidaps.utils.DateUtil
import org.json.JSONException
import org.json.JSONObject
fun BolusCalculatorResult.toJson(): JSONObject =
@ -14,11 +12,10 @@ fun BolusCalculatorResult.toJson(): JSONObject =
.put("eventType", TherapyEvent.Type.BOLUS_WIZARD)
.put("created_at", DateUtil.toISOString(timestamp))
.put("bolusCalculatorResult", Gson().toJson(this))
.put("date", timestamp).also {
if (glucoseValue != null) {
it.put("glucose", glucoseValue)
it.put("units", Constants.MGDL)
}
if (note != null) it.put("notes", note)
.put("date", timestamp)
.put("glucose", glucoseValue)
.put("units", Constants.MGDL)
.put("notes", note)
.also {
if (interfaceIDs.nightscoutId != null) it.put("_id", interfaceIDs.nightscoutId)
}

View file

@ -38,7 +38,7 @@ fun foodFromJson(jsonObject: JSONObject): Food? {
return null
}
fun Food.toJson(units: String): JSONObject =
fun Food.toJson(): JSONObject =
JSONObject()
.put("type", "food")
.put("name", name)

View file

@ -1,16 +1,10 @@
package info.nightscout.androidaps.utils.extensions
import androidx.work.ListenableWorker
import com.google.gson.Gson
import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.core.R
import info.nightscout.androidaps.data.Profile
import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.database.entities.TemporaryTarget
import info.nightscout.androidaps.database.entities.TherapyEvent
import info.nightscout.androidaps.database.transactions.SyncTemporaryTargetTransaction
import info.nightscout.androidaps.database.transactions.UpdateTemporaryTargetTransaction
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.DecimalFormatter
import info.nightscout.androidaps.utils.JsonHelper

View file

@ -7,6 +7,7 @@ import info.nightscout.androidaps.db.Treatment
import info.nightscout.androidaps.interfaces.ProfileStore
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.T
import info.nightscout.androidaps.utils.sharedPreferences.SP
import org.joda.time.DateTime
@ -19,9 +20,6 @@ import java.util.concurrent.TimeUnit
import javax.inject.Inject
import javax.inject.Singleton
/**
* Created by mike on 04.07.2016.
*/
@Singleton
class DanaPump @Inject constructor(
private val aapsLogger: AAPSLogger,
@ -38,6 +36,7 @@ class DanaPump @Inject constructor(
NOPRIME(0x10);
companion object {
private val map = values().associateBy(ErrorState::code)
operator fun get(value: Int) = map[value]
}
@ -286,9 +285,11 @@ class DanaPump @Inject constructor(
when (hwModel) {
0x01 -> "DanaR Korean"
0x03 ->
if (protocol == 0x00) "DanaR old"
else if (protocol == 0x02) "DanaR v2"
else "DanaR" // 0x01 and 0x03 known
when (protocol) {
0x00 -> "DanaR old"
0x02 -> "DanaR v2"
else -> "DanaR" // 0x01 and 0x03 known
}
0x05 ->
if (protocol < 10) "DanaRS"
else "DanaRS v3"
@ -297,7 +298,23 @@ class DanaPump @Inject constructor(
else -> "Unknown Dana pump"
}
fun pumpType(): PumpType =
when (hwModel) {
0x01 -> PumpType.DANA_R_KOREAN
0x03 ->
when (protocol) {
0x00 -> PumpType.DANA_R
0x02 -> PumpType.DANA_RV2
else -> PumpType.DANA_R // 0x01 and 0x03 known
}
0x05 -> PumpType.DANA_RS
0x06 -> PumpType.DANA_RS_KOREAN
0x07 -> PumpType.DANA_I
else -> PumpType.DANA_R
}
companion object {
const val UNITS_MGDL = 0
const val UNITS_MMOL = 1
const val DELIVERY_PRIME = 0x01

View file

@ -17,5 +17,4 @@ android {
dependencies {
implementation project(':core')
implementation project(':dana')
implementation project(':database')
}

View file

@ -38,8 +38,6 @@ import info.nightscout.androidaps.danar.comm.MsgStatusTempBasal;
import info.nightscout.androidaps.danar.services.AbstractDanaRExecutionService;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.data.PumpEnactResult;
import info.nightscout.androidaps.database.AppRepository;
import info.nightscout.androidaps.database.transactions.InsertTherapyEventAnnouncementTransaction;
import info.nightscout.androidaps.db.Treatment;
import info.nightscout.androidaps.dialogs.BolusProgressDialog;
import info.nightscout.androidaps.events.EventInitializationChanged;
@ -48,17 +46,18 @@ import info.nightscout.androidaps.events.EventPumpStatusChanged;
import info.nightscout.androidaps.interfaces.ActivePluginProvider;
import info.nightscout.androidaps.interfaces.CommandQueueProvider;
import info.nightscout.androidaps.interfaces.ProfileFunction;
import info.nightscout.androidaps.interfaces.PumpSync;
import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.plugins.bus.RxBusWrapper;
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker;
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification;
import info.nightscout.androidaps.plugins.pump.common.defs.PumpType;
import info.nightscout.androidaps.queue.commands.Command;
import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.T;
import info.nightscout.androidaps.utils.resources.ResourceHelper;
import io.reactivex.disposables.CompositeDisposable;
public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService {
@Inject AAPSLogger aapsLogger;
@ -72,9 +71,7 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService {
@Inject MessageHashTableRKorean messageHashTableRKorean;
@Inject ActivePluginProvider activePlugin;
@Inject ProfileFunction profileFunction;
@Inject AppRepository repository;
private final CompositeDisposable disposable = new CompositeDisposable();
@Inject PumpSync pumpSync;
public DanaRKoreanExecutionService() {
}
@ -202,7 +199,7 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService {
if (System.currentTimeMillis() > lastApproachingDailyLimit + 30 * 60 * 1000) {
Notification reportFail = new Notification(Notification.APPROACHING_DAILY_LIMIT, resourceHelper.gs(R.string.approachingdailylimit), Notification.URGENT);
rxBus.send(new EventNewNotification(reportFail));
disposable.add(repository.runTransaction(new InsertTherapyEventAnnouncementTransaction(resourceHelper.gs(R.string.approachingdailylimit) + ": " + danaPump.getDailyTotalUnits() + "/" + danaPump.getMaxDailyTotalUnits() + "U")).subscribe());
pumpSync.insertAnnouncement(resourceHelper.gs(R.string.approachingdailylimit) + ": " + danaPump.getDailyTotalUnits() + "/" + danaPump.getMaxDailyTotalUnits() + "U", null, PumpType.DANA_R_KOREAN, danaRKoreanPlugin.serialNumber());
lastApproachingDailyLimit = System.currentTimeMillis();
}
}

View file

@ -4,7 +4,6 @@ import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.danar.R
import info.nightscout.androidaps.danar.comm.MessageBase
import info.nightscout.androidaps.data.DetailedBolusInfo
import info.nightscout.androidaps.database.embedments.InterfaceIDs
import info.nightscout.androidaps.db.ExtendedBolus
import info.nightscout.androidaps.db.Source
import info.nightscout.androidaps.db.TemporaryBasal

View file

@ -52,8 +52,6 @@ import info.nightscout.androidaps.danar.comm.MsgStatusBasic;
import info.nightscout.androidaps.danar.services.AbstractDanaRExecutionService;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.data.PumpEnactResult;
import info.nightscout.androidaps.database.AppRepository;
import info.nightscout.androidaps.database.transactions.InsertTherapyEventAnnouncementTransaction;
import info.nightscout.androidaps.db.Treatment;
import info.nightscout.androidaps.dialogs.BolusProgressDialog;
import info.nightscout.androidaps.events.EventInitializationChanged;
@ -64,6 +62,7 @@ import info.nightscout.androidaps.interfaces.CommandQueueProvider;
import info.nightscout.androidaps.interfaces.ConfigBuilderInterface;
import info.nightscout.androidaps.interfaces.ProfileFunction;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.interfaces.PumpSync;
import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.plugins.bus.RxBusWrapper;
@ -72,13 +71,13 @@ import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotifi
import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewBolusProgress;
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification;
import info.nightscout.androidaps.plugins.pump.common.bolusInfo.DetailedBolusInfoStorage;
import info.nightscout.androidaps.plugins.pump.common.defs.PumpType;
import info.nightscout.androidaps.queue.Callback;
import info.nightscout.androidaps.queue.commands.Command;
import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.T;
import info.nightscout.androidaps.utils.resources.ResourceHelper;
import info.nightscout.androidaps.utils.sharedPreferences.SP;
import io.reactivex.disposables.CompositeDisposable;
public class DanaRv2ExecutionService extends AbstractDanaRExecutionService {
@Inject HasAndroidInjector injector;
@ -98,12 +97,11 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService {
@Inject DetailedBolusInfoStorage detailedBolusInfoStorage;
@Inject ActivePluginProvider activePluginProvider;
@Inject ProfileFunction profileFunction;
@Inject AppRepository repository;
@Inject PumpSync pumpSync;
@Inject SP sp;
@Inject DateUtil dateUtil;
private long lastHistoryFetched = 0;
private final CompositeDisposable disposable = new CompositeDisposable();
public DanaRv2ExecutionService() {
}
@ -251,7 +249,7 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService {
if (System.currentTimeMillis() > lastApproachingDailyLimit + 30 * 60 * 1000) {
Notification reportFail = new Notification(Notification.APPROACHING_DAILY_LIMIT, resourceHelper.gs(R.string.approachingdailylimit), Notification.URGENT);
rxBus.send(new EventNewNotification(reportFail));
disposable.add(repository.runTransaction(new InsertTherapyEventAnnouncementTransaction(resourceHelper.gs(R.string.approachingdailylimit) + ": " + danaPump.getDailyTotalUnits() + "/" + danaPump.getMaxDailyTotalUnits() + "U")).subscribe());
pumpSync.insertAnnouncement(resourceHelper.gs(R.string.approachingdailylimit) + ": " + danaPump.getDailyTotalUnits() + "/" + danaPump.getMaxDailyTotalUnits() + "U", null, PumpType.DANA_R_KOREAN, danaRKoreanPlugin.serialNumber());
lastApproachingDailyLimit = System.currentTimeMillis();
}
}

View file

@ -17,21 +17,19 @@ import info.nightscout.androidaps.dana.DanaPump;
import info.nightscout.androidaps.danaRKorean.DanaRKoreanPlugin;
import info.nightscout.androidaps.danaRv2.DanaRv2Plugin;
import info.nightscout.androidaps.danar.DanaRPlugin;
import info.nightscout.androidaps.database.AppRepository;
import info.nightscout.androidaps.interfaces.ActivePluginProvider;
import info.nightscout.androidaps.interfaces.CommandQueueProvider;
import info.nightscout.androidaps.interfaces.ConfigBuilderInterface;
import info.nightscout.androidaps.interfaces.DatabaseHelperInterface;
import info.nightscout.androidaps.interfaces.PumpSync;
import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.plugins.bus.RxBusWrapper;
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker;
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload;
import info.nightscout.androidaps.plugins.pump.common.bolusInfo.DetailedBolusInfoStorage;
import info.nightscout.androidaps.utils.CRC;
import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.resources.ResourceHelper;
import io.reactivex.disposables.CompositeDisposable;
/*
* 00 01 02 03 04 05 06
@ -53,12 +51,10 @@ public class MessageBase {
@Inject public CommandQueueProvider commandQueue;
@Inject public DetailedBolusInfoStorage detailedBolusInfoStorage;
@Inject public ConstraintChecker constraintChecker;
@Inject public AppRepository repository;
@Inject public PumpSync pumpSync;
@Inject public DatabaseHelperInterface databaseHelper;
HasAndroidInjector injector;
final CompositeDisposable disposable = new CompositeDisposable();
public byte[] buffer = new byte[512];
private int position = 6;
@ -67,7 +63,7 @@ public class MessageBase {
public MessageBase(HasAndroidInjector injector) {
injector.androidInjector().inject(this);
this. injector = injector;
this.injector = injector;
}
public void SetCommand(int cmd) {

View file

@ -2,10 +2,8 @@ package info.nightscout.androidaps.danar.comm
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.danar.R
import info.nightscout.androidaps.database.transactions.InsertTherapyEventAnnouncementTransaction
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewBolusProgress
import io.reactivex.rxkotlin.plusAssign
class MsgError(
injector: HasAndroidInjector
@ -36,6 +34,6 @@ class MsgError(
failed = false
}
aapsLogger.debug(LTag.PUMPCOMM, "Error detected: $errorString")
disposable += repository.runTransaction(InsertTherapyEventAnnouncementTransaction(errorString)).subscribe();
pumpSync.insertAnnouncement(errorString, null, danaPump.pumpType(), danaPump.serialNumber)
}
}

View file

@ -45,48 +45,41 @@ import info.nightscout.androidaps.danar.comm.MsgStatusBolusExtended;
import info.nightscout.androidaps.danar.comm.MsgStatusTempBasal;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.data.PumpEnactResult;
import info.nightscout.androidaps.database.AppRepository;
import info.nightscout.androidaps.database.transactions.InsertTherapyEventAnnouncementTransaction;
import info.nightscout.androidaps.db.Treatment;
import info.nightscout.androidaps.dialogs.BolusProgressDialog;
import info.nightscout.androidaps.events.EventInitializationChanged;
import info.nightscout.androidaps.events.EventProfileNeedsUpdate;
import info.nightscout.androidaps.events.EventPumpStatusChanged;
import info.nightscout.androidaps.interfaces.ActivePluginProvider;
import info.nightscout.androidaps.interfaces.CommandQueueProvider;
import info.nightscout.androidaps.interfaces.ProfileFunction;
import info.nightscout.androidaps.interfaces.PumpSync;
import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.plugins.bus.RxBusWrapper;
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker;
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewBolusProgress;
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification;
import info.nightscout.androidaps.plugins.pump.common.defs.PumpType;
import info.nightscout.androidaps.queue.Callback;
import info.nightscout.androidaps.queue.commands.Command;
import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.resources.ResourceHelper;
import info.nightscout.androidaps.utils.sharedPreferences.SP;
import io.reactivex.disposables.CompositeDisposable;
public class DanaRExecutionService extends AbstractDanaRExecutionService {
@Inject AAPSLogger aapsLogger;
@Inject RxBusWrapper rxBus;
@Inject ResourceHelper resourceHelper;
@Inject ConstraintChecker constraintChecker;
@Inject DanaPump danaPump;
@Inject DanaRPlugin danaRPlugin;
@Inject DanaRKoreanPlugin danaRKoreanPlugin;
@Inject CommandQueueProvider commandQueue;
@Inject MessageHashTableR messageHashTableR;
@Inject ActivePluginProvider activePlugin;
@Inject ProfileFunction profileFunction;
@Inject AppRepository repository;
@Inject PumpSync pumpSync;
@Inject SP sp;
@Inject HasAndroidInjector injector;
private final CompositeDisposable disposable = new CompositeDisposable();
public DanaRExecutionService() {
}
@ -215,7 +208,7 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService {
if (System.currentTimeMillis() > lastApproachingDailyLimit + 30 * 60 * 1000) {
Notification reportFail = new Notification(Notification.APPROACHING_DAILY_LIMIT, resourceHelper.gs(R.string.approachingdailylimit), Notification.URGENT);
rxBus.send(new EventNewNotification(reportFail));
disposable.add(repository.runTransaction(new InsertTherapyEventAnnouncementTransaction(resourceHelper.gs(R.string.approachingdailylimit) + ": " + danaPump.getDailyTotalUnits() + "/" + danaPump.getMaxDailyTotalUnits() + "U")).subscribe());
pumpSync.insertAnnouncement(resourceHelper.gs(R.string.approachingdailylimit) + ": " + danaPump.getDailyTotalUnits() + "/" + danaPump.getMaxDailyTotalUnits() + "U", null, PumpType.DANA_R_KOREAN, danaRKoreanPlugin.serialNumber());
lastApproachingDailyLimit = System.currentTimeMillis();
}
}

View file

@ -23,5 +23,4 @@ android {
dependencies {
implementation project(':core')
implementation project(':dana')
implementation project(':database')
}

View file

@ -5,14 +5,12 @@ import info.nightscout.androidaps.dana.DanaPump
import info.nightscout.androidaps.danars.R
import info.nightscout.androidaps.danars.encryption.BleEncryption
import info.nightscout.androidaps.data.DetailedBolusInfo
import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.database.entities.TherapyEvent
import info.nightscout.androidaps.database.transactions.InsertTherapyEventIfNewTransaction
import info.nightscout.androidaps.db.ExtendedBolus
import info.nightscout.androidaps.db.Source
import info.nightscout.androidaps.db.TemporaryBasal
import info.nightscout.androidaps.events.EventPumpStatusChanged
import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.PumpSync
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.pump.common.bolusInfo.DetailedBolusInfoStorage
@ -20,8 +18,6 @@ import info.nightscout.androidaps.plugins.pump.common.defs.PumpType
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.plusAssign
import org.joda.time.DateTime
import org.joda.time.DateTimeZone
import javax.inject.Inject
@ -37,9 +33,7 @@ open class DanaRS_Packet_APS_History_Events(
@Inject lateinit var danaPump: DanaPump
@Inject lateinit var detailedBolusInfoStorage: DetailedBolusInfoStorage
@Inject lateinit var sp: SP
@Inject lateinit var repository: AppRepository
private val disposable = CompositeDisposable()
@Inject lateinit var pumpSync: PumpSync
init {
opCode = BleEncryption.DANAR_PACKET__OPCODE__APS_HISTORY_EVENTS
@ -181,14 +175,12 @@ open class DanaRS_Packet_APS_History_Events(
DanaPump.REFILL -> {
aapsLogger.debug(LTag.PUMPCOMM, "[" + id + "] " + "EVENT REFILL (" + recordCode + ") " + dateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Amount: " + param1 / 100.0 + "U")
if (sp.getBoolean(R.string.key_rs_loginsulinchange, true))
disposable += repository.runTransactionForResult(InsertTherapyEventIfNewTransaction(
pumpSync.insertTherapyEventIfNewWithTimestamp(
timestamp = datetime,
type = TherapyEvent.Type.INSULIN_CHANGE,
note = resourceHelper.gs(R.string.danarspump),
glucoseUnit = TherapyEvent.GlucoseUnit.MGDL
)).subscribe(
{ result -> result.inserted.forEach { aapsLogger.debug(LTag.DATABASE, "Inserted therapy event $it") } },
{ aapsLogger.error(LTag.DATABASE, "Error while saving therapy event", it) }
type = DetailedBolusInfo.EventType.INSULIN_CHANGE,
pumpId = pumpId,
pumpType = danaPump.pumpType(),
pumpSerial = danaPump.serialNumber
)
status = "REFILL " + dateUtil.timeString(datetime)
}
@ -218,14 +210,12 @@ open class DanaRS_Packet_APS_History_Events(
DanaPump.PRIMECANNULA -> {
aapsLogger.debug(LTag.PUMPCOMM, "[" + id + "] " + "EVENT PRIMECANNULA(" + recordCode + ") " + dateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Amount: " + param1 / 100.0 + "U")
if (sp.getBoolean(R.string.key_rs_logcanulachange, true))
disposable += repository.runTransactionForResult(InsertTherapyEventIfNewTransaction(
pumpSync.insertTherapyEventIfNewWithTimestamp(
timestamp = datetime,
type = TherapyEvent.Type.CANNULA_CHANGE,
note = resourceHelper.gs(R.string.danarspump),
glucoseUnit = TherapyEvent.GlucoseUnit.MGDL
)).subscribe(
{ result -> result.inserted.forEach { aapsLogger.debug(LTag.DATABASE, "Inserted therapy event $it") } },
{ aapsLogger.error(LTag.DATABASE, "Error while saving therapy event", it) }
type = DetailedBolusInfo.EventType.CANNULA_CHANGE,
pumpId = pumpId,
pumpType = danaPump.pumpType(),
pumpSerial = danaPump.serialNumber
)
status = "PRIMECANNULA " + dateUtil.timeString(datetime)
}

View file

@ -1,17 +1,15 @@
package info.nightscout.androidaps.danars.comm
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.dana.DanaPump
import info.nightscout.androidaps.danars.R
import info.nightscout.androidaps.danars.encryption.BleEncryption
import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.database.transactions.InsertTherapyEventAnnouncementTransaction
import info.nightscout.androidaps.interfaces.PumpSync
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification
import info.nightscout.androidaps.utils.resources.ResourceHelper
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.plusAssign
import javax.inject.Inject
class DanaRS_Packet_Notify_Alarm(
@ -20,9 +18,8 @@ class DanaRS_Packet_Notify_Alarm(
@Inject lateinit var rxBus: RxBusWrapper
@Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var repository: AppRepository
private val disposable = CompositeDisposable()
@Inject lateinit var pumpSync: PumpSync
@Inject lateinit var danaPump: DanaPump
init {
type = BleEncryption.DANAR_PACKET__TYPE_NOTIFY
@ -69,7 +66,7 @@ class DanaRS_Packet_Notify_Alarm(
}
val notification = Notification(Notification.USER_MESSAGE, errorString, Notification.URGENT)
rxBus.send(EventNewNotification(notification))
disposable += repository.runTransaction(InsertTherapyEventAnnouncementTransaction(errorString)).subscribe()
pumpSync.insertAnnouncement(errorString, null, danaPump.pumpType(), danaPump.serialNumber)
}
override fun getFriendlyName(): String {

View file

@ -16,9 +16,8 @@ import info.nightscout.androidaps.danars.comm.DanaRS_Packet
import info.nightscout.androidaps.danars.comm.DanaRS_Packet_Etc_Keep_Connection
import info.nightscout.androidaps.danars.encryption.BleEncryption
import info.nightscout.androidaps.danars.events.EventDanaRSPairingSuccess
import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.database.transactions.InsertTherapyEventAnnouncementTransaction
import info.nightscout.androidaps.events.EventPumpStatusChanged
import info.nightscout.androidaps.interfaces.PumpSync
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
@ -32,8 +31,6 @@ import info.nightscout.androidaps.utils.extensions.notify
import info.nightscout.androidaps.utils.extensions.waitMillis
import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.plusAssign
import java.util.*
import java.util.concurrent.ScheduledFuture
import javax.inject.Inject
@ -51,7 +48,7 @@ class BLEComm @Inject internal constructor(
private val danaPump: DanaPump,
private val danaRSPlugin: DanaRSPlugin,
private val bleEncryption: BleEncryption,
private val repository: AppRepository
private val pumpSync: PumpSync
) {
companion object {
@ -64,8 +61,6 @@ class BLEComm @Inject internal constructor(
private const val PACKET_END_BYTE = 0x5A.toByte()
}
private val disposable = CompositeDisposable()
private var scheduledDisconnection: ScheduledFuture<*>? = null
private var processedMessage: DanaRS_Packet? = null
private val mSendQueue = ArrayList<ByteArray>()
@ -493,7 +488,7 @@ class BLEComm @Inject internal constructor(
aapsLogger.debug(LTag.PUMPBTCOMM, "<<<<< " + "ENCRYPTION__PUMP_CHECK (PUMP)" + " " + DanaRS_Packet.toHexString(decryptedBuffer))
mSendQueue.clear()
rxBus.send(EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTED, resourceHelper.gs(R.string.pumperror)))
disposable += repository.runTransaction(InsertTherapyEventAnnouncementTransaction(resourceHelper.gs(R.string.pumperror))).subscribe()
pumpSync.insertAnnouncement(resourceHelper.gs(R.string.pumperror), null, danaPump.pumpType(), danaPump.serialNumber)
val n = Notification(Notification.PUMP_ERROR, resourceHelper.gs(R.string.pumperror), Notification.URGENT)
rxBus.send(EventNewNotification(n))
// response BUSY: error status

View file

@ -18,8 +18,6 @@ import info.nightscout.androidaps.danars.R
import info.nightscout.androidaps.danars.comm.*
import info.nightscout.androidaps.data.Profile
import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.database.transactions.InsertTherapyEventAnnouncementTransaction
import info.nightscout.androidaps.db.Treatment
import info.nightscout.androidaps.dialogs.BolusProgressDialog
import info.nightscout.androidaps.events.EventAppExit
@ -29,6 +27,7 @@ import info.nightscout.androidaps.events.EventPumpStatusChanged
import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.CommandQueueProvider
import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.interfaces.PumpSync
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
@ -46,7 +45,6 @@ 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
import io.reactivex.rxkotlin.plusAssign
import org.joda.time.DateTime
import org.joda.time.DateTimeZone
import java.util.concurrent.TimeUnit
@ -73,7 +71,7 @@ class DanaRSService : DaggerService() {
@Inject lateinit var detailedBolusInfoStorage: DetailedBolusInfoStorage
@Inject lateinit var bleComm: BLEComm
@Inject lateinit var fabricPrivacy: FabricPrivacy
@Inject lateinit var repository: AppRepository
@Inject lateinit var pumpSync: PumpSync
@Inject lateinit var dateUtil: DateUtil
private val disposable = CompositeDisposable()
@ -208,7 +206,7 @@ class DanaRSService : DaggerService() {
if (System.currentTimeMillis() > lastApproachingDailyLimit + 30 * 60 * 1000) {
val reportFail = Notification(Notification.APPROACHING_DAILY_LIMIT, resourceHelper.gs(R.string.approachingdailylimit), Notification.URGENT)
rxBus.send(EventNewNotification(reportFail))
disposable += repository.runTransaction(InsertTherapyEventAnnouncementTransaction(resourceHelper.gs(R.string.approachingdailylimit) + ": " + danaPump.dailyTotalUnits + "/" + danaPump.maxDailyTotalUnits + "U")).subscribe()
pumpSync.insertAnnouncement(resourceHelper.gs(R.string.approachingdailylimit) + ": " + danaPump.dailyTotalUnits + "/" + danaPump.maxDailyTotalUnits + "U", null, danaPump.pumpType(), danaPump.serialNumber)
lastApproachingDailyLimit = System.currentTimeMillis()
}
}

View file

@ -1,5 +1,6 @@
package info.nightscout.androidaps.database
import info.nightscout.androidaps.database.embedments.InterfaceIDs
import info.nightscout.androidaps.database.entities.*
import info.nightscout.androidaps.database.interfaces.DBEntry
import info.nightscout.androidaps.database.transactions.Transaction
@ -277,6 +278,9 @@ open class AppRepository @Inject internal constructor(
database.bolusDao.getModifiedFrom(lastId)
.subscribeOn(Schedulers.io())
fun findBolusByPumpIds(pumpId: Long, pumpType: InterfaceIDs.PumpType, pumpSerial: String): Bolus? =
database.bolusDao.findByPumpIds(pumpId, pumpType, pumpSerial)
fun getBolusesDataFromTime(timestamp: Long, ascending: Boolean): Single<List<Bolus>> =
database.bolusDao.getBolusesFromTime(timestamp)
.map { if (!ascending) it.reversed() else it }
@ -314,6 +318,9 @@ open class AppRepository @Inject internal constructor(
database.carbsDao.getModifiedFrom(lastId)
.subscribeOn(Schedulers.io())
fun getCarbsByTimestamp(timestamp: Long): Carbs? =
database.carbsDao.findByTimestamp(timestamp)
fun getCarbsDataFromTime(timestamp: Long, ascending: Boolean): Single<List<Carbs>> =
database.carbsDao.getCarbsFromTime(timestamp)
.map { if (!ascending) it.reversed() else it }

View file

@ -3,6 +3,7 @@ package info.nightscout.androidaps.database.daos
import androidx.room.Dao
import androidx.room.Query
import info.nightscout.androidaps.database.TABLE_BOLUSES
import info.nightscout.androidaps.database.embedments.InterfaceIDs
import info.nightscout.androidaps.database.entities.Bolus
import io.reactivex.Maybe
import io.reactivex.Single
@ -17,6 +18,9 @@ internal interface BolusDao : TraceableDao<Bolus> {
@Query("DELETE FROM $TABLE_BOLUSES")
override fun deleteAllEntries()
@Query("SELECT * FROM $TABLE_BOLUSES WHERE pumpId = :pumpId AND pumpType = :pumpType AND pumpSerial = :pumpSerial AND referenceId IS NULL")
fun findByPumpIds(pumpId: Long, pumpType: InterfaceIDs.PumpType, pumpSerial: String): Bolus?
@Query("SELECT * FROM $TABLE_BOLUSES WHERE isValid = 1 AND timestamp >= :timestamp AND referenceId IS NULL ORDER BY id DESC")
fun getBolusesFromTime(timestamp: Long): Single<List<Bolus>>

View file

@ -3,7 +3,10 @@ package info.nightscout.androidaps.database.daos
import androidx.room.Dao
import androidx.room.Query
import info.nightscout.androidaps.database.TABLE_CARBS
import info.nightscout.androidaps.database.TABLE_THERAPY_EVENTS
import info.nightscout.androidaps.database.embedments.InterfaceIDs
import info.nightscout.androidaps.database.entities.Carbs
import info.nightscout.androidaps.database.entities.TherapyEvent
import io.reactivex.Maybe
import io.reactivex.Single
@ -17,6 +20,9 @@ internal interface CarbsDao : TraceableDao<Carbs> {
@Query("DELETE FROM $TABLE_CARBS")
override fun deleteAllEntries()
@Query("SELECT * FROM $TABLE_CARBS WHERE timestamp = :timestamp AND referenceId IS NULL")
fun findByTimestamp(timestamp: Long): Carbs?
@Query("SELECT * FROM $TABLE_CARBS WHERE isValid = 1 AND timestamp >= :timestamp AND referenceId IS NULL ORDER BY id DESC")
fun getCarbsFromTime(timestamp: Long): Single<List<Carbs>>

View file

@ -23,7 +23,9 @@ data class InterfaceIDs(
DANA_R,
DANA_R_KOREAN,
DANA_RV2,
DANA_I,
DANA_RS,
DANA_RS_KOREAN,
OMNIPOD_EROS,
OMNIPOD_DASH,
MEDTRONIC_512_517,

View file

@ -26,7 +26,7 @@ data class TherapyEvent(
override var isValid: Boolean = true,
override var referenceId: Long? = null,
@Embedded
override var interfaceIDs_backing: InterfaceIDs? = InterfaceIDs(),
override var interfaceIDs_backing: InterfaceIDs? = null,
override var timestamp: Long,
override var utcOffset: Long = TimeZone.getDefault().getOffset(timestamp).toLong(),
override var duration: Long = 0,

View file

@ -0,0 +1,41 @@
package info.nightscout.androidaps.database.transactions
import info.nightscout.androidaps.database.embedments.InterfaceIDs
import info.nightscout.androidaps.database.entities.Carbs
/**
* Creates Carbs if record doesn't exist
*/
class InsertIfNewByTimestampCarbsTransaction(
private val carbs: Carbs
) : Transaction<InsertIfNewByTimestampCarbsTransaction.TransactionResult>() {
constructor(
timestamp: Long,
amount: Double,
duration: Long,
interfaceIDs_backing: InterfaceIDs? = null
) : this(Carbs(
timestamp = timestamp,
amount = amount,
duration = duration,
interfaceIDs_backing = interfaceIDs_backing
))
override fun run(): TransactionResult {
val result = TransactionResult()
val current = database.carbsDao.findByTimestamp(carbs.timestamp)
if (current == null) {
database.carbsDao.insertNewEntry(carbs)
result.inserted.add(carbs)
} else
result.existing.add(carbs)
return result
}
class TransactionResult {
val inserted = mutableListOf<Carbs>()
val existing = mutableListOf<Carbs>()
}
}

View file

@ -2,9 +2,9 @@ package info.nightscout.androidaps.database.transactions
import info.nightscout.androidaps.database.entities.TherapyEvent
class InsertTherapyEventIfNewTransaction(
class InsertIfNewByTimestampTherapyEventTransaction(
val therapyEvent: TherapyEvent
) : Transaction<InsertTherapyEventIfNewTransaction.TransactionResult>() {
) : Transaction<InsertIfNewByTimestampTherapyEventTransaction.TransactionResult>() {
constructor(timestamp: Long, type: TherapyEvent.Type, duration: Long = 0, note: String? = null, enteredBy: String? = null, glucose: Double? = null, glucoseType: TherapyEvent.MeterType? = null, glucoseUnit: TherapyEvent.GlucoseUnit) :
this(TherapyEvent(timestamp = timestamp, type = type, duration = duration, note = note, enteredBy = enteredBy, glucose = glucose, glucoseType = glucoseType, glucoseUnit = glucoseUnit))

View file

@ -1,13 +1,28 @@
package info.nightscout.androidaps.database.transactions
import info.nightscout.androidaps.database.embedments.InterfaceIDs
import info.nightscout.androidaps.database.entities.TherapyEvent
class InsertTherapyEventAnnouncementTransaction(
val therapyEvent: TherapyEvent
) : Transaction<InsertTherapyEventAnnouncementTransaction.TransactionResult>() {
constructor(error: String) :
this(TherapyEvent(timestamp = System.currentTimeMillis(), type = TherapyEvent.Type.ANNOUNCEMENT, duration = 0, note = error, enteredBy = "AndroidAPS", glucose = null, glucoseType = null, glucoseUnit = TherapyEvent.GlucoseUnit.MGDL))
constructor(error: String, pumpId: Long? = null, pumpType: InterfaceIDs.PumpType? = null, pumpSerial: String? = null) :
this(
TherapyEvent(
timestamp = System.currentTimeMillis(),
type = TherapyEvent.Type.ANNOUNCEMENT,
duration = 0, note = error,
enteredBy = "AndroidAPS",
glucose = null,
glucoseType = null,
glucoseUnit = TherapyEvent.GlucoseUnit.MGDL,
interfaceIDs_backing = InterfaceIDs(
pumpId = pumpId,
pumpType = pumpType,
pumpSerial = pumpSerial)
)
)
override fun run(): TransactionResult {
val result = TransactionResult()

View file

@ -2,16 +2,18 @@ package info.nightscout.androidaps.database.transactions
import info.nightscout.androidaps.database.entities.TherapyEvent
class InvalidateAAPSStartedTherapyEventTransaction : Transaction<InvalidateAAPSStartedTherapyEventTransaction.TransactionResult>() {
class InvalidateAAPSStartedTherapyEventTransaction(private val note: String) : Transaction<InvalidateAAPSStartedTherapyEventTransaction.TransactionResult>() {
override fun run(): TransactionResult {
val result = TransactionResult()
val therapyEvents = database.therapyEventDao.getValidByType(TherapyEvent.Type.NOTE)
for (event in therapyEvents) {
if (event.note == note) {
event.isValid = false
database.therapyEventDao.updateExistingEntry(event)
result.invalidated.add(event)
}
}
return result
}

View file

@ -1,12 +1,22 @@
package info.nightscout.androidaps.database.transactions
class InvalidateBolusCalculatorResultTransaction(val id: Long) : Transaction<Unit>() {
import info.nightscout.androidaps.database.entities.BolusCalculatorResult
override fun run() {
class InvalidateBolusCalculatorResultTransaction(val id: Long) : Transaction<InvalidateBolusCalculatorResultTransaction.TransactionResult>() {
override fun run(): TransactionResult {
val result = TransactionResult()
val bolusCalculatorResult = database.bolusCalculatorResultDao.findById(id)
?: throw IllegalArgumentException("There is no such BolusCalculatorResult with the specified ID.")
bolusCalculatorResult.isValid = false
database.bolusCalculatorResultDao.updateExistingEntry(bolusCalculatorResult)
result.invalidated.add(bolusCalculatorResult)
return result
}
class TransactionResult {
val invalidated = mutableListOf<BolusCalculatorResult>()
}
}

View file

@ -1,11 +1,20 @@
package info.nightscout.androidaps.database.transactions
class InvalidateBolusTransaction(val id: Long) : Transaction<Unit>() {
import info.nightscout.androidaps.database.entities.Bolus
override fun run() {
class InvalidateBolusTransaction(val id: Long) : Transaction<InvalidateBolusTransaction.TransactionResult>() {
override fun run() : TransactionResult {
val result = TransactionResult()
val bolus = database.bolusDao.findById(id)
?: throw IllegalArgumentException("There is no such Bolus with the specified ID.")
bolus.isValid = false
database.bolusDao.updateExistingEntry(bolus)
result.invalidated.add(bolus)
return result
}
class TransactionResult {
val invalidated = mutableListOf<Bolus>()
}
}

View file

@ -1,11 +1,21 @@
package info.nightscout.androidaps.database.transactions
class InvalidateCarbsTransaction(val id: Long) : Transaction<Unit>() {
import info.nightscout.androidaps.database.entities.Carbs
override fun run() {
class InvalidateCarbsTransaction(val id: Long) : Transaction<InvalidateCarbsTransaction.TransactionResult>() {
override fun run(): TransactionResult {
val result = InvalidateCarbsTransaction.TransactionResult()
val carbs = database.carbsDao.findById(id)
?: throw IllegalArgumentException("There is no such Carbs with the specified ID.")
carbs.isValid = false
database.carbsDao.updateExistingEntry(carbs)
result.invalidated.add(carbs)
return result
}
class TransactionResult {
val invalidated = mutableListOf<Carbs>()
}
}

View file

@ -1,10 +1,21 @@
package info.nightscout.androidaps.database.transactions
class InvalidateTherapyEventTransaction(val id: Long) : Transaction<Unit>() {
override fun run() {
import info.nightscout.androidaps.database.entities.TherapyEvent
class InvalidateTherapyEventTransaction(val id: Long) : Transaction<InvalidateTherapyEventTransaction.TransactionResult>() {
override fun run(): TransactionResult {
val result = TransactionResult()
val therapyEvent = database.therapyEventDao.findById(id)
?: throw IllegalArgumentException("There is no such TherapyEvent with the specified ID.")
therapyEvent.isValid = false
database.therapyEventDao.updateExistingEntry(therapyEvent)
result.invalidated.add(therapyEvent)
return result
}
class TransactionResult {
val invalidated = mutableListOf<TherapyEvent>()
}
}

View file

@ -5,7 +5,7 @@ import info.nightscout.androidaps.database.entities.Food
/**
* Sync the TherapyEvents from NS
*/
class SyncFoodTransaction(private val food: Food) : Transaction<SyncFoodTransaction.TransactionResult>() {
class SyncNsFoodTransaction(private val food: Food) : Transaction<SyncNsFoodTransaction.TransactionResult>() {
override fun run(): TransactionResult {
val result = TransactionResult()

View file

@ -7,7 +7,7 @@ import kotlin.math.abs
/**
* Sync the TemporaryTarget from NS
*/
class SyncTemporaryTargetTransaction(private val temporaryTarget: TemporaryTarget) : Transaction<SyncTemporaryTargetTransaction.TransactionResult>() {
class SyncNsTemporaryTargetTransaction(private val temporaryTarget: TemporaryTarget) : Transaction<SyncNsTemporaryTargetTransaction.TransactionResult>() {
override fun run(): TransactionResult {
val result = TransactionResult()

View file

@ -5,7 +5,7 @@ import info.nightscout.androidaps.database.entities.TherapyEvent
/**
* Sync the TherapyEvents from NS
*/
class SyncTherapyEventTransaction(private val therapyEvent: TherapyEvent) : Transaction<SyncTherapyEventTransaction.TransactionResult>() {
class SyncNsTherapyEventTransaction(private val therapyEvent: TherapyEvent) : Transaction<SyncNsTherapyEventTransaction.TransactionResult>() {
override fun run(): TransactionResult {
val result = TransactionResult()

View file

@ -0,0 +1,36 @@
package info.nightscout.androidaps.database.transactions
import info.nightscout.androidaps.database.embedments.InsulinConfiguration
import info.nightscout.androidaps.database.embedments.InterfaceIDs
import info.nightscout.androidaps.database.entities.Bolus
import java.lang.IllegalStateException
/**
* Creates or updates the Bolus from pump synchronization
*/
class SyncPumpBolusTransaction(
private val bolus: Bolus,
) : Transaction<SyncPumpBolusTransaction.TransactionResult>() {
override fun run(): TransactionResult {
bolus.interfaceIDs.pumpId ?: bolus.interfaceIDs.pumpType ?: bolus.interfaceIDs.pumpSerial ?:
throw IllegalStateException("Some pump ID is null")
val result = TransactionResult()
val current = database.bolusDao.findByPumpIds(bolus.interfaceIDs.pumpId!!, bolus.interfaceIDs.pumpType!!, bolus.interfaceIDs.pumpSerial!!)
if (current == null) {
database.bolusDao.insertNewEntry(bolus)
result.inserted.add(bolus)
} else {
bolus.isValid = current.isValid
database.bolusDao.updateExistingEntry(bolus)
result.updated.add(bolus)
}
return result
}
class TransactionResult {
val inserted = mutableListOf<Bolus>()
val updated = mutableListOf<Bolus>()
}
}

View file

@ -17,5 +17,4 @@ android {
dependencies {
implementation project(':core')
implementation project(':database')
}

View file

@ -30,9 +30,6 @@ import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.data.PumpEnactResult;
import info.nightscout.androidaps.database.AppRepository;
import info.nightscout.androidaps.database.entities.TherapyEvent;
import info.nightscout.androidaps.database.transactions.InsertTherapyEventIfNewTransaction;
import info.nightscout.androidaps.db.ExtendedBolus;
import info.nightscout.androidaps.db.InsightBolusID;
import info.nightscout.androidaps.db.InsightHistoryOffset;
@ -55,6 +52,7 @@ import info.nightscout.androidaps.interfaces.ProfileFunction;
import info.nightscout.androidaps.interfaces.PumpDescription;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.interfaces.PumpPluginBase;
import info.nightscout.androidaps.interfaces.PumpSync;
import info.nightscout.androidaps.interfaces.TreatmentsInterface;
import info.nightscout.androidaps.interfaces.UploadQueueInterface;
import info.nightscout.androidaps.logging.AAPSLogger;
@ -136,7 +134,6 @@ import info.nightscout.androidaps.plugins.pump.insight.utils.ParameterBlockUtil;
import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.resources.ResourceHelper;
import info.nightscout.androidaps.utils.sharedPreferences.SP;
import io.reactivex.disposables.CompositeDisposable;
@Singleton
public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface, ConstraintsInterface, InsightConnectionService.StateCallback {
@ -153,7 +150,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface,
private final UploadQueueInterface uploadQueue;
private final DateUtil dateUtil;
private final DatabaseHelperInterface databaseHelper;
private final AppRepository repository;
private final PumpSync pumpSync;
public static final String ALERT_CHANNEL_ID = "AndroidAPS-InsightAlert";
@ -199,8 +196,6 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface,
private boolean statusLoaded;
private TBROverNotificationBlock tbrOverNotificationBlock;
private final CompositeDisposable disposable = new CompositeDisposable();
@Inject
public LocalInsightPlugin(
HasAndroidInjector injector,
@ -217,7 +212,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface,
ConfigInterface config,
DateUtil dateUtil,
DatabaseHelperInterface databaseHelper,
AppRepository repository
PumpSync pumpSync
) {
super(new PluginDescription()
.pluginIcon(R.drawable.ic_insight_128)
@ -242,7 +237,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface,
this.uploadQueue = uploadQueue;
this.dateUtil = dateUtil;
this.databaseHelper = databaseHelper;
this.repository = repository;
this.pumpSync = pumpSync;
pumpDescription = new PumpDescription();
pumpDescription.setPumpDescription(PumpType.ACCU_CHEK_INSIGHT_BLUETOOTH);
@ -1270,7 +1265,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface,
if (!sp.getBoolean("insight_log_site_changes", false)) return;
long timestamp = parseDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(),
event.getEventHour(), event.getEventMinute(), event.getEventSecond()) + timeOffset;
uploadCareportalEvent(timestamp, TherapyEvent.Type.CANNULA_CHANGE);
uploadCareportalEvent(timestamp, DetailedBolusInfo.EventType.CANNULA_CHANGE);
}
private void processTotalDailyDoseEvent(TotalDailyDoseEvent event) {
@ -1298,14 +1293,14 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface,
if (!sp.getBoolean("insight_log_reservoir_changes", false)) return;
long timestamp = parseDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(),
event.getEventHour(), event.getEventMinute(), event.getEventSecond()) + timeOffset;
uploadCareportalEvent(timestamp, TherapyEvent.Type.INSULIN_CHANGE);
uploadCareportalEvent(timestamp, DetailedBolusInfo.EventType.INSULIN_CHANGE);
}
private void processPowerUpEvent(PowerUpEvent event) {
if (!sp.getBoolean("insight_log_battery_changes", false)) return;
long timestamp = parseDate(event.getEventYear(), event.getEventMonth(), event.getEventDay(),
event.getEventHour(), event.getEventMinute(), event.getEventSecond()) + timeOffset;
uploadCareportalEvent(timestamp, TherapyEvent.Type.PUMP_BATTERY_CHANGE);
uploadCareportalEvent(timestamp, DetailedBolusInfo.EventType.PUMP_BATTERY_CHANGE);
}
private void processOperatingModeChangedEvent(String serial, List<InsightPumpID> pumpStartedEvents, OperatingModeChangedEvent event) {
@ -1555,12 +1550,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface,
}
private void logNote(long date, String note) {
if (repository.getTherapyEventByTimestamp(TherapyEvent.Type.NOTE, date) != null) return;
disposable.add(repository.runTransactionForResult(new InsertTherapyEventIfNewTransaction(date, TherapyEvent.Type.NOTE, 0, note, sp.getString("careportal_enteredby", "AndroidAPS"), null, null, TherapyEvent.GlucoseUnit.MGDL))
.subscribe(
result -> result.getInserted().forEach(event -> aapsLogger.debug(LTag.DATABASE, "Inserted therapy event " + event)),
error -> aapsLogger.error(LTag.DATABASE, "Error while saving therapy event", error)
));
pumpSync.insertTherapyEventIfNewWithTimestamp(date, DetailedBolusInfo.EventType.NOTE, note, null, PumpType.ACCU_CHEK_INSIGHT, serialNumber());
}
private long parseRelativeDate(int year, int month, int day, int hour, int minute, int second, int relativeHour, int relativeMinute, int relativeSecond) {
@ -1576,13 +1566,8 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface,
return calendar.getTimeInMillis();
}
private void uploadCareportalEvent(long date, TherapyEvent.Type event) {
if (repository.getTherapyEventByTimestamp(event, date) != null) return;
disposable.add(repository.runTransactionForResult(new InsertTherapyEventIfNewTransaction(date, event, 0, null, sp.getString("careportal_enteredby", "AndroidAPS"), null, null, TherapyEvent.GlucoseUnit.MGDL))
.subscribe(
result -> result.getInserted().forEach(record -> aapsLogger.debug(LTag.DATABASE, "Inserted therapy event " + record)),
error -> aapsLogger.error(LTag.DATABASE, "Error while saving therapy event", error)
));
private void uploadCareportalEvent(long date, DetailedBolusInfo.EventType event) {
pumpSync.insertTherapyEventIfNewWithTimestamp(date, event, null, null, PumpType.ACCU_CHEK_INSIGHT, serialNumber());
}
@NonNull @Override

View file

@ -17,5 +17,4 @@ android {
dependencies {
implementation project(':core')
implementation project(':rileylink')
implementation project(':database')
}

View file

@ -32,7 +32,6 @@ import info.nightscout.androidaps.activities.ErrorHelperActivity;
import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.data.PumpEnactResult;
import info.nightscout.androidaps.database.entities.Bolus;
import info.nightscout.androidaps.db.Source;
import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.events.EventRefreshOverview;
@ -55,7 +54,6 @@ 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.events.EventRefreshButtonState;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkConst;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkUtil;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkPumpDevice;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkPumpInfo;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkServiceState;
@ -101,7 +99,6 @@ import info.nightscout.androidaps.utils.sharedPreferences.SP;
public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInterface, RileyLinkPumpDevice {
private final SP sp;
private final RileyLinkUtil rileyLinkUtil;
private final MedtronicUtil medtronicUtil;
private final MedtronicPumpStatus medtronicPumpStatus;
private final MedtronicHistoryData medtronicHistoryData;
@ -133,7 +130,6 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
SP sp,
CommandQueueProvider commandQueue,
FabricPrivacy fabricPrivacy,
RileyLinkUtil rileyLinkUtil,
MedtronicUtil medtronicUtil,
MedtronicPumpStatus medtronicPumpStatus,
MedtronicHistoryData medtronicHistoryData,
@ -155,7 +151,6 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
injector, resourceHelper, aapsLogger, commandQueue, rxBus, activePlugin, sp, context, fabricPrivacy, dateUtil, aapsSchedulers
);
this.rileyLinkUtil = rileyLinkUtil;
this.medtronicUtil = medtronicUtil;
this.sp = sp;
this.medtronicPumpStatus = medtronicPumpStatus;

View file

@ -21,9 +21,6 @@ import javax.inject.Singleton;
import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.database.AppRepository;
import info.nightscout.androidaps.database.entities.TherapyEvent;
import info.nightscout.androidaps.database.transactions.InsertTherapyEventIfNewTransaction;
import info.nightscout.androidaps.db.DbObjectBase;
import info.nightscout.androidaps.db.ExtendedBolus;
import info.nightscout.androidaps.db.Source;
@ -32,6 +29,7 @@ import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.db.Treatment;
import info.nightscout.androidaps.interfaces.ActivePluginProvider;
import info.nightscout.androidaps.interfaces.DatabaseHelperInterface;
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;
@ -54,7 +52,6 @@ import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil;
import info.nightscout.androidaps.plugins.treatments.TreatmentUpdateReturn;
import info.nightscout.androidaps.utils.Round;
import info.nightscout.androidaps.utils.sharedPreferences.SP;
import io.reactivex.disposables.CompositeDisposable;
/**
@ -80,7 +77,7 @@ public class MedtronicHistoryData {
private final MedtronicPumpHistoryDecoder medtronicPumpHistoryDecoder;
private final MedtronicPumpStatus medtronicPumpStatus;
private final DatabaseHelperInterface databaseHelper;
private final AppRepository repository;
private final PumpSync pumpSync;
private final List<PumpHistoryEntry> allHistory;
private List<PumpHistoryEntry> newHistory = null;
@ -94,10 +91,9 @@ public class MedtronicHistoryData {
private long lastIdUsed = 0;
private final CompositeDisposable disposable = new CompositeDisposable();
/**
* Double bolus debug. We seem to have small problem with double Boluses (or sometimes also missing boluses
* from history. This flag turns on debugging for that (default is off=false)... Debuging is pretty detailed,
* from history. This flag turns on debugging for that (default is off=false)... Debugging is pretty detailed,
* so log files will get bigger.
* Note: June 2020. Since this seems to be fixed, I am disabling this per default. I will leave code inside
* in case we need it again. Code that turns this on is commented out RileyLinkMedtronicService#verifyConfiguration()
@ -114,7 +110,7 @@ public class MedtronicHistoryData {
MedtronicPumpHistoryDecoder medtronicPumpHistoryDecoder,
MedtronicPumpStatus medtronicPumpStatus,
DatabaseHelperInterface databaseHelperInterface,
AppRepository repository
PumpSync pumpSync
) {
this.allHistory = new ArrayList<>();
@ -126,7 +122,7 @@ public class MedtronicHistoryData {
this.medtronicPumpHistoryDecoder = medtronicPumpHistoryDecoder;
this.medtronicPumpStatus = medtronicPumpStatus;
this.databaseHelper = databaseHelperInterface;
this.repository = repository;
this.pumpSync = pumpSync;
}
private Gson gson() {
@ -552,7 +548,7 @@ public class MedtronicHistoryData {
long lastPrimeFromAAPS = sp.getLong(MedtronicConst.Statistics.LastPrime, 0L);
if (lastPrimeRecord != lastPrimeFromAAPS) {
uploadCareportalEvent(DateTimeUtil.toMillisFromATD(lastPrimeRecord), TherapyEvent.Type.CANNULA_CHANGE);
uploadCareportalEvent(DateTimeUtil.toMillisFromATD(lastPrimeRecord), DetailedBolusInfo.EventType.CANNULA_CHANGE);
sp.putLong(MedtronicConst.Statistics.LastPrime, lastPrimeRecord);
}
@ -575,7 +571,7 @@ public class MedtronicHistoryData {
long lastRewindFromAAPS = sp.getLong(MedtronicConst.Statistics.LastRewind, 0L);
if (lastRewindRecord != lastRewindFromAAPS) {
uploadCareportalEvent(DateTimeUtil.toMillisFromATD(lastRewindRecord), TherapyEvent.Type.INSULIN_CHANGE);
uploadCareportalEvent(DateTimeUtil.toMillisFromATD(lastRewindRecord), DetailedBolusInfo.EventType.INSULIN_CHANGE);
sp.putLong(MedtronicConst.Statistics.LastRewind, lastRewindRecord);
}
@ -583,15 +579,8 @@ public class MedtronicHistoryData {
}
private void uploadCareportalEvent(long date, TherapyEvent.Type event) {
if (repository.getTherapyEventByTimestamp(event, date) != null) return;
disposable.add(repository.runTransactionForResult(new InsertTherapyEventIfNewTransaction(date,
event, 0, null, sp.getString("careportal_enteredby", "AndroidAPS"),
null, null, TherapyEvent.GlucoseUnit.MGDL))
.subscribe(
result -> result.getInserted().forEach(record -> aapsLogger.debug(LTag.DATABASE, "Inserted therapy event " + record)),
error -> aapsLogger.error(LTag.DATABASE, "Error while saving therapy event", error)
));
private void uploadCareportalEvent(long date, DetailedBolusInfo.EventType event) {
pumpSync.insertTherapyEventIfNewWithTimestamp(date, event, null, null, medtronicPumpStatus.pumpType, medtronicPumpStatus.serialNumber);
}
private void processTDDs(List<PumpHistoryEntry> tddsIn) {

View file

@ -18,5 +18,4 @@ dependencies {
implementation project(':core')
implementation project(':omnipod-common')
implementation project(':rileylink')
implementation project(':database')
}

View file

@ -33,8 +33,6 @@ import info.nightscout.androidaps.activities.ErrorHelperActivity;
import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.data.PumpEnactResult;
import info.nightscout.androidaps.database.AppRepository;
import info.nightscout.androidaps.database.transactions.InsertTherapyEventAnnouncementTransaction;
import info.nightscout.androidaps.db.ExtendedBolus;
import info.nightscout.androidaps.db.Source;
import info.nightscout.androidaps.db.TemporaryBasal;
@ -50,6 +48,7 @@ import info.nightscout.androidaps.interfaces.ProfileFunction;
import info.nightscout.androidaps.interfaces.PumpDescription;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.interfaces.PumpPluginBase;
import info.nightscout.androidaps.interfaces.PumpSync;
import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.plugins.bus.RxBusWrapper;
@ -141,7 +140,7 @@ public class OmnipodErosPumpPlugin extends PumpPluginBase implements PumpInterfa
private final PumpDescription pumpDescription;
private final ServiceConnection serviceConnection;
private final PumpType pumpType = PumpType.OMNIPOD_EROS;
private final AppRepository repository;
private final PumpSync pumpSync;
private final CompositeDisposable disposable = new CompositeDisposable();
@ -178,7 +177,7 @@ public class OmnipodErosPumpPlugin extends PumpPluginBase implements PumpInterfa
RileyLinkUtil rileyLinkUtil,
OmnipodAlertUtil omnipodAlertUtil,
ProfileFunction profileFunction,
AppRepository repository
PumpSync pumpSync
) {
super(new PluginDescription() //
.mainType(PluginType.PUMP) //
@ -205,7 +204,7 @@ public class OmnipodErosPumpPlugin extends PumpPluginBase implements PumpInterfa
this.rileyLinkUtil = rileyLinkUtil;
this.omnipodAlertUtil = omnipodAlertUtil;
this.profileFunction = profileFunction;
this.repository = repository;
this.pumpSync = pumpSync;
pumpDescription = new PumpDescription(pumpType);
@ -408,7 +407,7 @@ public class OmnipodErosPumpPlugin extends PumpPluginBase implements PumpInterfa
String notificationText = resourceHelper.gq(R.plurals.omnipod_common_pod_alerts, activeAlerts.size(), alerts);
Notification notification = new Notification(Notification.OMNIPOD_POD_ALERTS, notificationText, Notification.URGENT);
rxBus.send(new EventNewNotification(notification));
disposable.add(repository.runTransaction(new InsertTherapyEventAnnouncementTransaction(notificationText)).subscribe());
pumpSync.insertAnnouncement(notificationText, null, PumpType.OMNIPOD_EROS, serialNumber());
if (aapsOmnipodErosManager.isAutomaticallyAcknowledgeAlertsEnabled() && !getCommandQueue().isCustomCommandInQueue(CommandAcknowledgeAlerts.class)) {
queueAcknowledgeAlertsCommand();
@ -420,7 +419,7 @@ public class OmnipodErosPumpPlugin extends PumpPluginBase implements PumpInterfa
private void handlePodFaultEvent() {
if (podStateManager.isPodFaulted()) {
String notificationText = resourceHelper.gs(R.string.omnipod_common_pod_status_pod_fault_description, podStateManager.getFaultEventCode().getValue(), podStateManager.getFaultEventCode().name());
disposable.add(repository.runTransaction(new InsertTherapyEventAnnouncementTransaction(notificationText)).subscribe());
pumpSync.insertAnnouncement(notificationText, null, PumpType.OMNIPOD_EROS, serialNumber());
}
}

View file

@ -18,9 +18,6 @@ import info.nightscout.androidaps.activities.ErrorHelperActivity;
import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.data.PumpEnactResult;
import info.nightscout.androidaps.database.AppRepository;
import info.nightscout.androidaps.database.entities.TherapyEvent;
import info.nightscout.androidaps.database.transactions.InsertTherapyEventIfNewTransaction;
import info.nightscout.androidaps.db.OmnipodHistoryRecord;
import info.nightscout.androidaps.db.Source;
import info.nightscout.androidaps.db.TemporaryBasal;
@ -28,6 +25,7 @@ import info.nightscout.androidaps.events.Event;
import info.nightscout.androidaps.events.EventRefreshOverview;
import info.nightscout.androidaps.interfaces.ActivePluginProvider;
import info.nightscout.androidaps.interfaces.DatabaseHelperInterface;
import info.nightscout.androidaps.interfaces.PumpSync;
import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.plugins.bus.RxBusWrapper;
@ -85,7 +83,6 @@ import info.nightscout.androidaps.plugins.pump.omnipod.eros.util.OmnipodAlertUti
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;
import io.reactivex.subjects.SingleSubject;
@Singleton
@ -103,7 +100,7 @@ public class AapsOmnipodErosManager {
private final DatabaseHelperInterface databaseHelper;
private final OmnipodAlertUtil omnipodAlertUtil;
private final Context context;
private final AppRepository repository;
private final PumpSync pumpSync;
private boolean basalBeepsEnabled;
private boolean bolusBeepsEnabled;
@ -120,8 +117,6 @@ public class AapsOmnipodErosManager {
private boolean showRileyLinkBatteryLevel;
private boolean batteryChangeLoggingEnabled;
private final CompositeDisposable disposable = new CompositeDisposable();
@Inject
public AapsOmnipodErosManager(OmnipodRileyLinkCommunicationManager communicationService,
PodStateManager podStateManager,
@ -136,7 +131,7 @@ public class AapsOmnipodErosManager {
DatabaseHelperInterface databaseHelper,
OmnipodAlertUtil omnipodAlertUtil,
Context context,
AppRepository repository) {
PumpSync pumpSync) {
this.podStateManager = podStateManager;
this.aapsOmnipodUtil = aapsOmnipodUtil;
@ -149,7 +144,7 @@ public class AapsOmnipodErosManager {
this.databaseHelper = databaseHelper;
this.omnipodAlertUtil = omnipodAlertUtil;
this.context = context;
this.repository = repository;
this.pumpSync = pumpSync;
delegate = new OmnipodManager(aapsLogger, aapsSchedulers, communicationService, podStateManager);
@ -218,8 +213,8 @@ public class AapsOmnipodErosManager {
addToHistory(System.currentTimeMillis(), PodHistoryEntryType.INSERT_CANNULA, result.getComment(), result.getSuccess());
if (result.getSuccess()) {
uploadCareportalEvent(System.currentTimeMillis() - 1000, TherapyEvent.Type.INSULIN_CHANGE);
uploadCareportalEvent(System.currentTimeMillis(), TherapyEvent.Type.CANNULA_CHANGE);
uploadCareportalEvent(System.currentTimeMillis() - 1000, DetailedBolusInfo.EventType.INSULIN_CHANGE);
uploadCareportalEvent(System.currentTimeMillis(), DetailedBolusInfo.EventType.CANNULA_CHANGE);
dismissNotification(Notification.OMNIPOD_POD_NOT_ATTACHED);
@ -999,13 +994,8 @@ public class AapsOmnipodErosManager {
return new BasalSchedule(entries);
}
private void uploadCareportalEvent(long date, TherapyEvent.Type event) {
if (repository.getTherapyEventByTimestamp(event, date) != null) return;
disposable.add(repository.runTransactionForResult(new InsertTherapyEventIfNewTransaction(date, event, 0, null, sp.getString("careportal_enteredby", "AndroidAPS"), null, null, TherapyEvent.GlucoseUnit.MGDL))
.subscribe(
result -> result.getInserted().forEach(record -> aapsLogger.debug(LTag.DATABASE, "Inserted therapy event " + record)),
error -> aapsLogger.error(LTag.DATABASE, "Error while saving therapy event", error)
));
private void uploadCareportalEvent(long date, DetailedBolusInfo.EventType event) {
pumpSync.insertTherapyEventIfNewWithTimestamp(date, event, null, null, PumpType.OMNIPOD_EROS, Integer.toString(podStateManager.getAddress()));
}
public String serialNumber() {