Merge pull request #3093 from Jackenmen/handle_finger_bg_in_medtronic_driver

Auto-add "BG Check" treatment for Contour Link readings
This commit is contained in:
Milos Kozak 2023-12-05 12:42:38 +01:00 committed by GitHub
commit 51a832f51b
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
9 changed files with 245 additions and 14 deletions

View file

@ -1,5 +1,6 @@
package app.aaps.core.interfaces.pump
import app.aaps.core.interfaces.db.GlucoseUnit
import app.aaps.core.interfaces.profile.Profile
import app.aaps.core.interfaces.pump.defs.PumpType
import app.aaps.core.interfaces.utils.DateUtil
@ -257,6 +258,26 @@ interface PumpSync {
**/
fun insertTherapyEventIfNewWithTimestamp(timestamp: Long, type: DetailedBolusInfo.EventType, note: String? = null, pumpId: Long? = null, pumpType: PumpType, pumpSerial: String): Boolean
/**
* Synchronization of FINGER_STICK_BG_VALUE events
*
* 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 glucose glucose value
* @param glucoseUnit glucose unit
* @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
* @return true if new record is created
**/
fun insertFingerBgIfNewWithTimestamp(timestamp: Long, glucose: Double, glucoseUnit: GlucoseUnit, note: String? = null, pumpId: Long? = null, pumpType: PumpType, pumpSerial: String): Boolean
/**
* Create an announcement
*

View file

@ -1,5 +1,6 @@
package app.aaps.implementation.pump
import app.aaps.core.interfaces.db.GlucoseUnit
import app.aaps.core.interfaces.logging.AAPSLogger
import app.aaps.core.interfaces.logging.LTag
import app.aaps.core.interfaces.logging.UserEntryLogger
@ -16,6 +17,7 @@ import app.aaps.core.interfaces.sharedPreferences.SP
import app.aaps.core.interfaces.utils.DateUtil
import app.aaps.core.interfaces.utils.T
import app.aaps.core.main.events.EventNewNotification
import app.aaps.core.main.extensions.fromConstant
import app.aaps.core.main.pump.fromDbPumpType
import app.aaps.core.main.pump.toDbPumpType
import app.aaps.core.main.pump.toDbSource
@ -291,6 +293,42 @@ class PumpSyncImplementation @Inject constructor(
}
}
override fun insertFingerBgIfNewWithTimestamp(timestamp: Long, glucose: Double, glucoseUnit: GlucoseUnit, note: String?, pumpId: Long?, pumpType: PumpType, pumpSerial: String): Boolean {
if (!confirmActivePump(timestamp, pumpType, pumpSerial)) return false
var type = TherapyEvent.Type.FINGER_STICK_BG_VALUE
val therapyEvent = TherapyEvent(
timestamp = timestamp,
type = type,
duration = 0,
note = note,
enteredBy = "AndroidAPS",
glucose = glucose,
glucoseType = TherapyEvent.MeterType.FINGER,
glucoseUnit = TherapyEvent.GlucoseUnit.fromConstant(glucoseUnit),
interfaceIDs_backing = InterfaceIDs(
pumpId = pumpId,
pumpType = pumpType.toDbPumpType(),
pumpSerial = pumpSerial
)
)
uel.log(
action = UserEntry.Action.CAREPORTAL,
source = pumpType.source.toDbSource(),
note = note,
timestamp = timestamp,
ValueWithUnit.Timestamp(timestamp), ValueWithUnit.TherapyEventType(type)
)
repository.runTransactionForResult(InsertIfNewByTimestampTherapyEventTransaction(therapyEvent))
.doOnError {
aapsLogger.error(LTag.DATABASE, "Error while saving TherapyEvent", it)
}
.blockingGet()
.also { result ->
result.inserted.forEach { aapsLogger.debug(LTag.DATABASE, "Inserted TherapyEvent $it") }
return result.inserted.size > 0
}
}
override fun insertAnnouncement(error: String, pumpId: Long?, pumpType: PumpType, pumpSerial: String) {
if (!confirmActivePump(dateUtil.now(), pumpType, pumpSerial)) return
disposable += repository.runTransaction(InsertTherapyEventAnnouncementTransaction(error, pumpId, pumpType.toDbPumpType(), pumpSerial))

View file

@ -153,7 +153,6 @@ class MedtronicPumpHistoryDecoder @Inject constructor(
PumpHistoryEntryType.ClearAlarm,
PumpHistoryEntryType.ChangeAlarmNotifyMode,
PumpHistoryEntryType.EnableDisableRemote,
PumpHistoryEntryType.BGReceived,
PumpHistoryEntryType.SensorAlert,
PumpHistoryEntryType.ChangeTimeFormat,
PumpHistoryEntryType.ChangeReservoirWarningTime,
@ -188,7 +187,6 @@ class MedtronicPumpHistoryDecoder @Inject constructor(
PumpHistoryEntryType.ChangeWatchdogEnable,
PumpHistoryEntryType.ChangeOtherDeviceID,
PumpHistoryEntryType.ReadOtherDevicesIDs,
PumpHistoryEntryType.BGReceived512,
PumpHistoryEntryType.SensorStatus,
PumpHistoryEntryType.ReadCaptureEventEnabled,
PumpHistoryEntryType.ChangeCaptureEventEnable,
@ -206,6 +204,12 @@ class MedtronicPumpHistoryDecoder @Inject constructor(
PumpHistoryEntryType.UnabsorbedInsulin,
PumpHistoryEntryType.UnabsorbedInsulin512 -> RecordDecodeStatus.Ignored
PumpHistoryEntryType.BGReceived,
PumpHistoryEntryType.BGReceived512 -> {
decodeBgReceived(entry)
RecordDecodeStatus.OK
}
PumpHistoryEntryType.DailyTotals522,
PumpHistoryEntryType.DailyTotals523,
PumpHistoryEntryType.DailyTotals515,
@ -409,8 +413,11 @@ class MedtronicPumpHistoryDecoder @Inject constructor(
}
private fun decodeBgReceived(entry: PumpHistoryEntry) {
entry.addDecodedData("amount", (ByteUtil.asUINT8(entry.getRawDataByIndex(0)) shl 3) + (ByteUtil.asUINT8(entry.getRawDataByIndex(3)) shr 5))
entry.addDecodedData("meter", ByteUtil.substring(entry.rawData, 6, 3)) // index moved from 1 -> 0
val glucoseMgdl = (ByteUtil.asUINT8(entry.head[0]) shl 3) + (ByteUtil.asUINT8(entry.datetime[2]) shr 5)
val meterSerial = ByteUtil.shortHexStringWithoutSpaces(entry.body)
entry.addDecodedData("GlucoseMgdl", glucoseMgdl)
entry.addDecodedData("MeterSerial", meterSerial)
entry.displayableValue = String.format("Glucose: %d mg/dl, Meter Serial: %s", glucoseMgdl, meterSerial)
}
private fun decodeCalBGForPH(entry: PumpHistoryEntry) {

View file

@ -4,6 +4,7 @@ import app.aaps.core.interfaces.logging.AAPSLogger
import app.aaps.core.interfaces.logging.LTag
import app.aaps.core.interfaces.notifications.Notification
import app.aaps.core.interfaces.plugin.ActivePlugin
import app.aaps.core.interfaces.profile.ProfileUtil
import app.aaps.core.interfaces.pump.DetailedBolusInfo
import app.aaps.core.interfaces.pump.PumpSync
import app.aaps.core.interfaces.pump.defs.PumpType
@ -67,7 +68,8 @@ class MedtronicHistoryData @Inject constructor(
val medtronicPumpStatus: MedtronicPumpStatus,
private val pumpSync: PumpSync,
private val pumpSyncStorage: PumpSyncStorage,
private val uiInteraction: UiInteraction
private val uiInteraction: UiInteraction,
private val profileUtil: ProfileUtil
) {
val allHistory: MutableList<PumpHistoryEntry> = mutableListOf()
@ -322,6 +324,17 @@ class MedtronicHistoryData @Inject constructor(
* Process History Data: Boluses(Treatments), TDD, TBRs, Suspend-Resume (or other pump stops: battery, prime)
*/
fun processNewHistoryData() {
// Finger BG (for adding entry to careportal)
val bgRecords: MutableList<PumpHistoryEntry> = getFilteredItems(setOf(PumpHistoryEntryType.BGReceived, PumpHistoryEntryType.BGReceived512))
aapsLogger.debug(LTag.PUMP, String.format(Locale.ENGLISH, "ProcessHistoryData: BGReceived [count=%d, items=%s]", bgRecords.size, gson.toJson(bgRecords)))
if (isCollectionNotEmpty(bgRecords)) {
try {
processBgReceived(bgRecords)
} catch (ex: Exception) {
aapsLogger.error(LTag.PUMP, "ProcessHistoryData: Error processing BGReceived entries: " + ex.message, ex)
throw ex
}
}
// Prime (for resetting autosense)
val primeRecords: MutableList<PumpHistoryEntry> = getFilteredItems(PumpHistoryEntryType.Prime)
@ -419,6 +432,34 @@ class MedtronicHistoryData @Inject constructor(
}
}
fun processBgReceived(bgRecords: List<PumpHistoryEntry>) {
for (bgRecord in bgRecords) {
val glucoseMgdl = bgRecord.getDecodedDataEntry("GlucoseMgdl")
if (glucoseMgdl == null || glucoseMgdl as Int == 0) {
continue
}
val glucose = profileUtil.fromMgdlToUnits(glucoseMgdl.toDouble())
val glucoseUnit = profileUtil.units
val result = pumpSync.insertFingerBgIfNewWithTimestamp(
DateTimeUtil.toMillisFromATD(bgRecord.atechDateTime),
glucose, glucoseUnit, null,
bgRecord.pumpId,
medtronicPumpStatus.pumpType,
medtronicPumpStatus.serialNumber
)
aapsLogger.debug(
LTag.PUMP, String.format(
Locale.ROOT, "insertFingerBgIfNewWithTimestamp [date=%d, glucose=%f, glucoseUnit=%s, pumpId=%d, pumpSerial=%s] - Result: %b",
bgRecord.atechDateTime, glucose, glucoseUnit, bgRecord.pumpId,
medtronicPumpStatus.serialNumber, result
)
)
}
}
private fun processPrime(primeRecords: List<PumpHistoryEntry>) {
val maxAllowedTimeInPast = DateTimeUtil.getATDWithAddedMinutes(GregorianCalendar(), -30)
var lastPrimeRecordTime = 0L

View file

@ -4,7 +4,7 @@ import app.aaps.core.interfaces.plugin.ActivePlugin
import app.aaps.core.interfaces.pump.PumpSync
import app.aaps.core.interfaces.resources.ResourceHelper
import app.aaps.core.interfaces.sharedPreferences.SP
import app.aaps.shared.tests.TestBase
import app.aaps.shared.tests.TestBaseWithProfile
import dagger.android.AndroidInjector
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkUtil
@ -16,15 +16,13 @@ import info.nightscout.pump.common.sync.PumpSyncStorage
import org.mockito.Answers
import org.mockito.Mock
open class MedtronicTestBase : TestBase() {
open class MedtronicTestBase : TestBaseWithProfile() {
var rileyLinkUtil = RileyLinkUtil()
@Mock lateinit var pumpSync: PumpSync
@Mock lateinit var pumpSyncStorage: PumpSyncStorage
@Mock(answer = Answers.RETURNS_DEEP_STUBS) lateinit var activePlugin: ActivePlugin
@Mock lateinit var sp: SP
@Mock lateinit var rh: ResourceHelper
@Mock(answer = Answers.RETURNS_DEEP_STUBS) override lateinit var activePlugin: ActivePlugin
lateinit var medtronicUtil: MedtronicUtil
lateinit var decoder: MedtronicPumpHistoryDecoder
@ -53,6 +51,24 @@ open class MedtronicTestBase : TestBase() {
}
fun getPumpHistoryEntryFromData(vararg elements: Int): PumpHistoryEntry {
val data: MutableList<Byte> = ArrayList()
for (item in elements) {
var b = if (item > 128) item - 256 else item
data.add(b.toByte());
}
val entryType = PumpHistoryEntryType.getByCode(data[0])
val phe = PumpHistoryEntry()
phe.setEntryType(medtronicUtil.medtronicPumpModel, entryType)
phe.setData(data, false)
decoder.decodeRecord(phe)
return phe
}
private fun preProcessTBRs(tbrsInput: MutableList<PumpHistoryEntry>): MutableList<PumpHistoryEntry> {
val tbrs: MutableList<PumpHistoryEntry> = mutableListOf()
val map: MutableMap<String?, PumpHistoryEntry?> = HashMap()

View file

@ -40,7 +40,7 @@ import org.mockito.Mock
decoder = MedtronicPumpHistoryDecoder(aapsLogger, medtronicUtil)
medtronicHistoryData = MedtronicHistoryData(
packetInjector, aapsLogger, sp, rh, rxBus, activePlugin,
medtronicUtil, decoder, medtronicPumpStatus, pumpSync, pumpSyncStorage, uiInteraction
medtronicUtil, decoder, medtronicPumpStatus, pumpSync, pumpSyncStorage, uiInteraction, profileUtil
)

View file

@ -1,8 +1,16 @@
package info.nightscout.androidaps.plugins.pump.medtronic.comm.history.pump
import app.aaps.core.interfaces.ui.UiInteraction
import info.nightscout.androidaps.plugins.pump.medtronic.MedtronicTestBase
import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.pump.MedtronicPumpHistoryDecoder
import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicDeviceType
import info.nightscout.androidaps.plugins.pump.medtronic.driver.MedtronicPumpStatus
import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil
import com.google.common.truth.Truth.assertThat
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.mockito.Mock
import org.mockito.Mockito.`when`
/**
* Created by andy on 4/9/19.
@ -10,6 +18,16 @@ import org.junit.jupiter.api.Test
*/
class PumpHistoryEntryUTest : MedtronicTestBase() {
@Mock lateinit var medtronicPumpStatus: MedtronicPumpStatus
@Mock lateinit var uiInteraction: UiInteraction
@BeforeEach
fun setUp() {
medtronicUtil = MedtronicUtil(aapsLogger, rxBus, rileyLinkUtil, medtronicPumpStatus, uiInteraction)
`when`(medtronicUtil.medtronicPumpModel).thenReturn(MedtronicDeviceType.Medtronic_723_Revel)
decoder = MedtronicPumpHistoryDecoder(aapsLogger, medtronicUtil)
}
@Test
fun checkIsAfter() {
val dateObject = 20191010000000L
@ -18,4 +36,21 @@ class PumpHistoryEntryUTest : MedtronicTestBase() {
phe.atechDateTime = dateObject
assertThat(phe.isAfter(queryObject)).isTrue()
}
@Test
fun decodeBgReceived() {
val bgRecord = getPumpHistoryEntryFromData(
// head
0x39, 0x15,
// datetime (combined with glucose in mg/dl)
0xC2, 0x25, 0xF3, 0x61, 0x17,
// serial number
0x12, 0x34, 0x56
)
val expectedGlucoseMgdl = 175
val expectedMeterSerial = "123456"
assertThat(bgRecord.getDecodedDataEntry("GlucoseMgdl")).isEqualTo(expectedGlucoseMgdl)
assertThat(bgRecord.getDecodedDataEntry("MeterSerial")).isEqualTo(expectedMeterSerial)
}
}

View file

@ -1,18 +1,24 @@
package info.nightscout.androidaps.plugins.pump.medtronic.data
import app.aaps.core.interfaces.db.GlucoseUnit
import app.aaps.core.interfaces.ui.UiInteraction
import app.aaps.core.utils.DateTimeUtil
import com.google.gson.Gson
import com.google.gson.internal.LinkedTreeMap
import com.google.gson.reflect.TypeToken
import info.nightscout.androidaps.plugins.pump.medtronic.MedtronicTestBase
import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.pump.MedtronicPumpHistoryDecoder
import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.pump.PumpHistoryEntry
import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.pump.PumpHistoryEntryType
import info.nightscout.androidaps.plugins.pump.medtronic.data.dto.TempBasalPair
import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicDeviceType
import info.nightscout.androidaps.plugins.pump.medtronic.driver.MedtronicPumpStatus
import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.mockito.Mock
import org.mockito.Mockito.verify
import org.mockito.Mockito.`when`
import java.lang.reflect.Type
@Suppress("UNCHECKED_CAST")
@ -24,6 +30,7 @@ class MedtronicHistoryDataUTest : MedtronicTestBase() {
@BeforeEach
fun setUp() {
medtronicUtil = MedtronicUtil(aapsLogger, rxBus, rileyLinkUtil, medtronicPumpStatus, uiInteraction)
`when`(medtronicUtil.medtronicPumpModel).thenReturn(MedtronicDeviceType.Medtronic_723_Revel)
decoder = MedtronicPumpHistoryDecoder(aapsLogger, medtronicUtil)
}
@ -32,7 +39,7 @@ class MedtronicHistoryDataUTest : MedtronicTestBase() {
val unitToTest = MedtronicHistoryData(
packetInjector, aapsLogger, sp, rh, rxBus, activePlugin,
medtronicUtil, decoder, medtronicPumpStatus, pumpSync, pumpSyncStorage, uiInteraction
medtronicUtil, decoder, medtronicPumpStatus, pumpSync, pumpSyncStorage, uiInteraction, profileUtil
)
val gson = Gson()
@ -75,7 +82,7 @@ class MedtronicHistoryDataUTest : MedtronicTestBase() {
medtronicUtil, decoder,
medtronicPumpStatus,
pumpSync,
pumpSyncStorage, uiInteraction
pumpSyncStorage, uiInteraction, profileUtil
)
val gson = Gson()
@ -110,4 +117,70 @@ class MedtronicHistoryDataUTest : MedtronicTestBase() {
}
@Test
fun processBgReceived_WithMgdl() {
val unitToTest = MedtronicHistoryData(
packetInjector, aapsLogger, sp, rh, rxBus, activePlugin,
medtronicUtil, decoder,
medtronicPumpStatus,
pumpSync,
pumpSyncStorage, uiInteraction, profileUtil
)
val glucoseMgdl = 175
`when`(sp.getString(app.aaps.core.utils.R.string.key_units, GlucoseUnit.MGDL.asText)).thenReturn(GlucoseUnit.MGDL.asText)
val bgRecord = PumpHistoryEntry()
bgRecord.setEntryType(medtronicUtil.medtronicPumpModel, PumpHistoryEntryType.BGReceived)
bgRecord.addDecodedData("GlucoseMgdl", glucoseMgdl)
bgRecord.addDecodedData("MeterSerial", "123456")
unitToTest.processBgReceived(listOf(bgRecord))
verify(pumpSync).insertFingerBgIfNewWithTimestamp(
DateTimeUtil.toMillisFromATD(bgRecord.atechDateTime),
glucoseMgdl.toDouble(),
GlucoseUnit.MGDL, null,
bgRecord.pumpId,
medtronicPumpStatus.pumpType,
medtronicPumpStatus.serialNumber
)
}
@Test
fun processBgReceived_WithMmol() {
val unitToTest = MedtronicHistoryData(
packetInjector, aapsLogger, sp, rh, rxBus, activePlugin,
medtronicUtil, decoder,
medtronicPumpStatus,
pumpSync,
pumpSyncStorage, uiInteraction, profileUtil
)
val glucoseMgdl = 180
val glucoseMmol = 10.0
`when`(sp.getString(app.aaps.core.utils.R.string.key_units, GlucoseUnit.MGDL.asText)).thenReturn(GlucoseUnit.MMOL.asText)
val bgRecord = PumpHistoryEntry()
bgRecord.setEntryType(medtronicUtil.medtronicPumpModel, PumpHistoryEntryType.BGReceived)
bgRecord.addDecodedData("GlucoseMgdl", glucoseMgdl)
bgRecord.addDecodedData("MeterSerial", "123456")
unitToTest.processBgReceived(listOf(bgRecord))
verify(pumpSync).insertFingerBgIfNewWithTimestamp(
DateTimeUtil.toMillisFromATD(bgRecord.atechDateTime),
glucoseMmol,
GlucoseUnit.MMOL, null,
bgRecord.pumpId,
medtronicPumpStatus.pumpType,
medtronicPumpStatus.serialNumber
)
}
}

View file

@ -36,7 +36,7 @@ import org.mockito.invocation.InvocationOnMock
@Suppress("SpellCheckingInspection")
open class TestBaseWithProfile : TestBase() {
@Mock lateinit var activePlugin: ActivePlugin
@Mock open lateinit var activePlugin: ActivePlugin
@Mock lateinit var rh: ResourceHelper
@Mock lateinit var iobCobCalculator: IobCobCalculator
@Mock lateinit var fabricPrivacy: FabricPrivacy