Merge branch 'dev' into mdt_new_fix_2

This commit is contained in:
Andy Rozman 2021-06-20 19:45:03 +01:00
commit e30c5162ef
25 changed files with 253 additions and 68 deletions

View file

@ -363,7 +363,7 @@ class ImportExportPrefsImpl @Inject constructor(
override fun exportUserEntriesCsv(activity: FragmentActivity, singleEntries: Single<List<UserEntry>>) {
val entries = singleEntries.blockingGet()
prefFileList.ensureExportDirExists()
val newFile = prefFileList.newExportXmlFile()
val newFile = prefFileList.newExportCsvFile()
try {
classicPrefsFormat.saveCsv(newFile, entries)

View file

@ -16,11 +16,13 @@ import info.nightscout.androidaps.events.EventNewBG
import info.nightscout.androidaps.insight.database.InsightDatabase
import info.nightscout.androidaps.interfaces.DataSyncSelector
import info.nightscout.androidaps.interfaces.ImportExportPrefs
import info.nightscout.androidaps.interfaces.IobCobCalculator
import info.nightscout.androidaps.interfaces.PumpSync
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.UserEntryLogger
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.general.maintenance.activities.LogSettingActivity
import info.nightscout.androidaps.plugins.general.overview.OverviewData
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventNewHistoryData
import info.nightscout.androidaps.utils.alertDialogs.OKDialog
import info.nightscout.androidaps.utils.resources.ResourceHelper
@ -44,6 +46,8 @@ class MaintenanceFragment : DaggerFragment() {
@Inject lateinit var uel: UserEntryLogger
@Inject lateinit var dataSyncSelector: DataSyncSelector
@Inject lateinit var pumpSync: PumpSync
@Inject lateinit var iobCobCalculator: IobCobCalculator
@Inject lateinit var overviewData: OverviewData
private val compositeDisposable = CompositeDisposable()
@ -77,6 +81,9 @@ class MaintenanceFragment : DaggerFragment() {
insightDatabase.clearAllTables()
dataSyncSelector.resetToNextFullSync()
pumpSync.connectNewPump()
overviewData.reset()
iobCobCalculator.ads.reset()
iobCobCalculator.clearCache()
}
.subscribeOn(aapsSchedulers.io)
.observeOn(aapsSchedulers.main)

View file

@ -54,7 +54,7 @@ class MaintenancePlugin @Inject constructor(
val recipient = sp.getString(R.string.key_maintenance_logs_email, "logs@androidaps.org")
val amount = sp.getInt(R.string.key_maintenance_logs_amount, 2)
val logs = getLogFiles(amount)
val zipDir = fileListProvider.ensureExportDirExists()
val zipDir = fileListProvider.ensureTempDirExists()
val zipFile = File(zipDir, constructName())
aapsLogger.debug("zipFile: ${zipFile.absolutePath}")
val zip = zipLogs(zipFile, logs)
@ -75,7 +75,7 @@ class MaintenancePlugin @Inject constructor(
val files = logDir.listFiles { _: File?, name: String ->
(name.startsWith("AndroidAPS") && name.endsWith(".zip"))
}
Arrays.sort(files) { f1: File, f2: File -> f1.name.compareTo(f2.name) }
Arrays.sort(files) { f1: File, f2: File -> f2.name.compareTo(f1.name) }
var delFiles = listOf(*files)
val amount = sp.getInt(R.string.key_logshipper_amount, keep)
val keepIndex = amount - 1
@ -85,7 +85,7 @@ class MaintenancePlugin @Inject constructor(
file.delete()
}
}
val exportDir = fileListProvider.ensureExportDirExists()
val exportDir = fileListProvider.ensureTempDirExists()
if (exportDir.exists()) {
val expFiles = exportDir.listFiles()
for (file in expFiles) {

View file

@ -71,6 +71,44 @@ class OverviewData @Inject constructor(
var fromTime: Long = 0
var endTime: Long = 0
fun reset() {
profile = null
profileName = null
profileNameWithRemainingTime = null
calcProgress = ""
lastBg = null
temporaryBasal = null
extendedBolus = null
bolusIob = null
basalIob = null
cobInfo = null
lastCarbsTime = 0L
temporaryTarget = null
lastAutosensData = null
bgReadingsArray = ArrayList()
bucketedGraphSeries = PointsWithLabelGraphSeries()
bgReadingGraphSeries = PointsWithLabelGraphSeries()
predictionsGraphSeries = PointsWithLabelGraphSeries()
baseBasalGraphSeries = LineGraphSeries()
tempBasalGraphSeries = LineGraphSeries()
basalLineGraphSeries = LineGraphSeries()
absoluteBasalGraphSeries = LineGraphSeries()
activitySeries = FixedLineGraphSeries()
activityPredictionSeries = FixedLineGraphSeries()
iobSeries = FixedLineGraphSeries()
absIobSeries = FixedLineGraphSeries()
iobPredictions1Series = PointsWithLabelGraphSeries()
iobPredictions2Series = PointsWithLabelGraphSeries()
minusBgiSeries = FixedLineGraphSeries()
minusBgiHistSeries = FixedLineGraphSeries()
cobSeries = FixedLineGraphSeries()
cobMinFailOverSeries = PointsWithLabelGraphSeries()
deviationsSeries = BarGraphSeries()
ratioSeries = LineGraphSeries()
dsMaxSeries = LineGraphSeries()
dsMinSeries = LineGraphSeries()
}
fun initRange() {
rangeToDisplay = sp.getInt(R.string.key_rangetodisplay, 6)

View file

@ -1,13 +1,16 @@
package info.nightscout.androidaps.plugins.general.smsCommunicator
import android.os.SystemClock
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.R
import info.nightscout.androidaps.interfaces.CommandQueueProvider
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.plugins.general.smsCommunicator.otp.OneTimePassword
import info.nightscout.androidaps.plugins.general.smsCommunicator.otp.OneTimePasswordValidationResult
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.T
import info.nightscout.androidaps.utils.resources.ResourceHelper
import javax.inject.Inject
@ -23,6 +26,7 @@ class AuthRequest internal constructor(
@Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var otp: OneTimePassword
@Inject lateinit var dateUtil: DateUtil
@Inject lateinit var commandQueue: CommandQueueProvider
private var date = 0L
private var processed = false
@ -49,6 +53,19 @@ class AuthRequest internal constructor(
}
if (dateUtil.now() - date < Constants.SMS_CONFIRM_TIMEOUT) {
processed = true
if (action.pumpCommand) {
val start = dateUtil.now()
//wait for empty queue
while (start + T.mins(3).msecs() > dateUtil.now()) {
if (commandQueue.size() == 0) break
SystemClock.sleep(100)
}
if (commandQueue.size() != 0) {
aapsLogger.debug(LTag.SMS, "Command timed out: " + requester.text)
smsCommunicatorPlugin.sendSMS(Sms(requester.phoneNumber, resourceHelper.gs(R.string.sms_timeout_while_wating)))
return
}
}
aapsLogger.debug(LTag.SMS, "Processing confirmed SMS: " + requester.text)
action.run()
return

View file

@ -1,37 +1,37 @@
package info.nightscout.androidaps.plugins.general.smsCommunicator
abstract class SmsAction : Runnable {
abstract class SmsAction(val pumpCommand: Boolean) : Runnable {
var aDouble: Double? = null
var anInteger: Int? = null
var secondInteger: Int? = null
var secondLong: Long? = null
var aString: String? = null
internal constructor()
internal constructor(aDouble: Double) {
internal constructor(pumpCommand: Boolean, aDouble: Double) : this(pumpCommand) {
this.aDouble = aDouble
}
internal constructor(aDouble: Double, secondInteger: Int) {
internal constructor(pumpCommand: Boolean, aDouble: Double, secondInteger: Int) : this(pumpCommand) {
this.aDouble = aDouble
this.secondInteger = secondInteger
}
internal constructor(aString: String, secondInteger: Int) {
internal constructor(pumpCommand: Boolean, aString: String, secondInteger: Int) : this(pumpCommand) {
this.aString = aString
this.secondInteger = secondInteger
}
internal constructor(anInteger: Int) {
internal constructor(pumpCommand: Boolean, anInteger: Int) : this(pumpCommand) {
this.anInteger = anInteger
}
internal constructor(anInteger: Int, secondInteger: Int) {
internal constructor(pumpCommand: Boolean, anInteger: Int, secondInteger: Int) : this(pumpCommand) {
this.anInteger = anInteger
this.secondInteger = secondInteger
}
internal constructor(anInteger: Int, secondLong: Long) {
internal constructor(pumpCommand: Boolean, anInteger: Int, secondLong: Long) : this(pumpCommand) {
this.anInteger = anInteger
this.secondLong = secondLong
}

View file

@ -94,8 +94,8 @@ class SmsCommunicatorPlugin @Inject constructor(
private val disposable = CompositeDisposable()
var allowedNumbers: MutableList<String> = ArrayList()
var messageToConfirm: AuthRequest? = null
var lastRemoteBolusTime: Long = 0
@Volatile var messageToConfirm: AuthRequest? = null
@Volatile var lastRemoteBolusTime: Long = 0
var messages = ArrayList<Sms>()
val commands = mapOf(
@ -278,6 +278,7 @@ class SmsCommunicatorPlugin @Inject constructor(
else sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat)))
"BOLUS" ->
if (!remoteCommandsAllowed) sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.smscommunicator_remotecommandnotallowed)))
else if (commandQueue.bolusInQueue()) sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.smscommunicator_another_bolus_in_queue)))
else if (divided.size == 2 && dateUtil.now() - lastRemoteBolusTime < minDistance) sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.smscommunicator_remotebolusnotallowed)))
else if (divided.size == 2 && pump.isSuspended()) sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.pumpsuspended)))
else if (divided.size == 2 || divided.size == 3) processBOLUS(divided, receivedSms)
@ -303,9 +304,13 @@ class SmsCommunicatorPlugin @Inject constructor(
else sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat)))
else ->
if (messageToConfirm?.requester?.phoneNumber == receivedSms.phoneNumber) {
messageToConfirm?.action(divided[0])
val execute = messageToConfirm
messageToConfirm = null
} else sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.smscommunicator_unknowncommand)))
execute?.action(divided[0])
} else {
messageToConfirm = null
sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.smscommunicator_unknowncommand)))
}
}
}
rxBus.send(EventSmsCommunicatorUpdateGui())
@ -344,7 +349,7 @@ class SmsCommunicatorPlugin @Inject constructor(
val passCode = generatePassCode()
val reply = String.format(resourceHelper.gs(R.string.smscommunicator_loopdisablereplywithcode), passCode)
receivedSms.processed = true
messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction() {
messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = false) {
override fun run() {
uel.log(Action.LOOP_DISABLED, Sources.SMS)
loop.enabled = false
@ -368,10 +373,10 @@ class SmsCommunicatorPlugin @Inject constructor(
val passCode = generatePassCode()
val reply = String.format(resourceHelper.gs(R.string.smscommunicator_loopenablereplywithcode), passCode)
receivedSms.processed = true
messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction() {
messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = false) {
override fun run() {
uel.log(Action.LOOP_ENABLED, Sources.SMS)
loop.enabled= true
loop.enabled = true
sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.smscommunicator_loophasbeenenabled)))
rxBus.send(EventRefreshOverview("SMS_LOOP_START"))
}
@ -395,7 +400,7 @@ class SmsCommunicatorPlugin @Inject constructor(
val passCode = generatePassCode()
val reply = String.format(resourceHelper.gs(R.string.smscommunicator_loopresumereplywithcode), passCode)
receivedSms.processed = true
messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction() {
messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = true) {
override fun run() {
uel.log(Action.RESUME, Sources.SMS)
disposable += repository.runTransactionForResult(CancelCurrentOfflineEventIfAnyTransaction(dateUtil.now()))
@ -432,7 +437,7 @@ class SmsCommunicatorPlugin @Inject constructor(
val passCode = generatePassCode()
val reply = String.format(resourceHelper.gs(R.string.smscommunicator_suspendreplywithcode), duration, passCode)
receivedSms.processed = true
messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(duration) {
messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = true, duration) {
override fun run() {
uel.log(Action.SUSPEND, Sources.SMS)
commandQueue.cancelTempBasal(true, object : Callback() {
@ -478,7 +483,7 @@ class SmsCommunicatorPlugin @Inject constructor(
@kotlin.ExperimentalStdlibApi
private fun processHELP(divided: Array<String>, receivedSms: Sms) {
when {
divided.size == 1 -> {
divided.size == 1 -> {
sendSMS(Sms(receivedSms.phoneNumber, commands.keys.toString().replace("[", "").replace("]", "")))
receivedSms.processed = true
}
@ -490,7 +495,7 @@ class SmsCommunicatorPlugin @Inject constructor(
}
}
else -> sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat)))
else -> sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat)))
}
}
@ -513,7 +518,7 @@ class SmsCommunicatorPlugin @Inject constructor(
val passCode = generatePassCode()
val reply = String.format(resourceHelper.gs(R.string.smscommunicator_pumpconnectwithcode), passCode)
receivedSms.processed = true
messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction() {
messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = true) {
override fun run() {
uel.log(Action.RECONNECT, Sources.SMS)
commandQueue.cancelTempBasal(true, object : Callback() {
@ -546,7 +551,7 @@ class SmsCommunicatorPlugin @Inject constructor(
val passCode = generatePassCode()
val reply = String.format(resourceHelper.gs(R.string.smscommunicator_pumpdisconnectwithcode), duration, passCode)
receivedSms.processed = true
messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction() {
messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = true) {
override fun run() {
uel.log(Action.DISCONNECT, Sources.SMS)
val profile = profileFunction.getProfile() ?: return
@ -601,7 +606,7 @@ class SmsCommunicatorPlugin @Inject constructor(
val reply = String.format(resourceHelper.gs(R.string.smscommunicator_profilereplywithcode), list[pIndex - 1], percentage, passCode)
receivedSms.processed = true
val finalPercentage = percentage
messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(list[pIndex - 1] as String, finalPercentage) {
messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = true, list[pIndex - 1] as String, finalPercentage) {
override fun run() {
profileFunction.createProfileSwitch(store, list[pIndex - 1] as String, 0, finalPercentage, 0, dateUtil.now())
val replyText = resourceHelper.gs(R.string.profileswitchcreated)
@ -622,7 +627,7 @@ class SmsCommunicatorPlugin @Inject constructor(
val passCode = generatePassCode()
val reply = String.format(resourceHelper.gs(R.string.smscommunicator_basalstopreplywithcode), passCode)
receivedSms.processed = true
messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction() {
messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = true) {
override fun run() {
commandQueue.cancelTempBasal(true, object : Callback() {
override fun run() {
@ -657,7 +662,7 @@ class SmsCommunicatorPlugin @Inject constructor(
val passCode = generatePassCode()
val reply = String.format(resourceHelper.gs(R.string.smscommunicator_basalpctreplywithcode), tempBasalPct, duration, passCode)
receivedSms.processed = true
messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(tempBasalPct, duration) {
messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = true, tempBasalPct, duration) {
override fun run() {
commandQueue.tempBasalPercent(anInteger(), secondInteger(), true, profile, PumpSync.TemporaryBasalType.NORMAL, object : Callback() {
override fun run() {
@ -701,7 +706,7 @@ class SmsCommunicatorPlugin @Inject constructor(
val passCode = generatePassCode()
val reply = String.format(resourceHelper.gs(R.string.smscommunicator_basalreplywithcode), tempBasal, duration, passCode)
receivedSms.processed = true
messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(tempBasal, duration) {
messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = true, tempBasal, duration) {
override fun run() {
commandQueue.tempBasalAbsolute(aDouble(), secondInteger(), true, profile, PumpSync.TemporaryBasalType.NORMAL, object : Callback() {
override fun run() {
@ -739,7 +744,7 @@ class SmsCommunicatorPlugin @Inject constructor(
val passCode = generatePassCode()
val reply = String.format(resourceHelper.gs(R.string.smscommunicator_extendedstopreplywithcode), passCode)
receivedSms.processed = true
messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction() {
messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = true) {
override fun run() {
commandQueue.cancelExtended(object : Callback() {
override fun run() {
@ -769,7 +774,7 @@ class SmsCommunicatorPlugin @Inject constructor(
val passCode = generatePassCode()
val reply = String.format(resourceHelper.gs(R.string.smscommunicator_extendedreplywithcode), extended, duration, passCode)
receivedSms.processed = true
messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(extended, duration) {
messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = true, extended, duration) {
override fun run() {
commandQueue.extendedBolus(aDouble(), secondInteger(), object : Callback() {
override fun run() {
@ -815,7 +820,7 @@ class SmsCommunicatorPlugin @Inject constructor(
else
String.format(resourceHelper.gs(R.string.smscommunicator_bolusreplywithcode), bolus, passCode)
receivedSms.processed = true
messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(bolus) {
messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = true, bolus) {
override fun run() {
val detailedBolusInfo = DetailedBolusInfo()
detailedBolusInfo.insulin = aDouble()
@ -917,7 +922,7 @@ class SmsCommunicatorPlugin @Inject constructor(
val passCode = generatePassCode()
val reply = String.format(resourceHelper.gs(R.string.smscommunicator_carbsreplywithcode), grams, dateUtil.timeString(time), passCode)
receivedSms.processed = true
messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(grams, time) {
messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = true, grams, time) {
override fun run() {
val detailedBolusInfo = DetailedBolusInfo()
detailedBolusInfo.carbs = anInteger().toDouble()
@ -954,7 +959,7 @@ class SmsCommunicatorPlugin @Inject constructor(
val passCode = generatePassCode()
val reply = String.format(resourceHelper.gs(R.string.smscommunicator_temptargetwithcode), divided[1].uppercase(Locale.getDefault()), passCode)
receivedSms.processed = true
messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction() {
messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = false) {
override fun run() {
val units = profileFunction.getUnits()
var keyDuration = 0
@ -1016,7 +1021,7 @@ class SmsCommunicatorPlugin @Inject constructor(
val passCode = generatePassCode()
val reply = String.format(resourceHelper.gs(R.string.smscommunicator_temptargetcancel), passCode)
receivedSms.processed = true
messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction() {
messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = false) {
override fun run() {
disposable += repository.runTransactionForResult(CancelCurrentTemporaryTargetIfAnyTransaction(dateUtil.now()))
.subscribe({ result ->
@ -1041,7 +1046,7 @@ class SmsCommunicatorPlugin @Inject constructor(
val passCode = generatePassCode()
val reply = String.format(resourceHelper.gs(R.string.smscommunicator_stopsmswithcode), passCode)
receivedSms.processed = true
messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction() {
messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = false) {
override fun run() {
sp.putBoolean(R.string.key_smscommunicator_remotecommandsallowed, false)
val replyText = String.format(resourceHelper.gs(R.string.smscommunicator_stoppedsms))
@ -1059,7 +1064,7 @@ class SmsCommunicatorPlugin @Inject constructor(
val passCode = generatePassCode()
val reply = String.format(resourceHelper.gs(R.string.smscommunicator_calibrationreplywithcode), cal, passCode)
receivedSms.processed = true
messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(cal) {
messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = false, cal) {
override fun run() {
val result = xdripCalibrations.sendIntent(aDouble!!)
val replyText =

View file

@ -130,7 +130,7 @@ open class IobCobCalculatorPlugin @Inject constructor(
runCalculation(reason, System.currentTimeMillis(), bgDataReload = false, limitDataToOldestAvailable = true, cause = event)
}
fun clearCache() {
override fun clearCache() {
synchronized(dataLock) {
aapsLogger.debug(LTag.AUTOSENS, "Clearing cached data.")
iobTable = LongSparseArray()

View file

@ -68,12 +68,12 @@ open class CommandQueue @Inject constructor(
private val disposable = CompositeDisposable()
private val queue = LinkedList<Command>()
private var thread: QueueThread? = null
@Volatile private var thread: QueueThread? = null
var performing: Command? = null
@Volatile var performing: Command? = null
init {
disposable.add(rxBus
disposable += rxBus
.toObservable(EventProfileSwitchChanged::class.java)
.observeOn(aapsSchedulers.io)
.subscribe({
@ -109,8 +109,6 @@ open class CommandQueue @Inject constructor(
})
}
}, fabricPrivacy::logException)
)
}
private fun executingNowError(): PumpEnactResult =
@ -197,6 +195,7 @@ open class CommandQueue @Inject constructor(
aapsLogger.debug(LTag.PUMPQUEUE, "Starting new queue")
val tempCommandQueue = CommandQueue(injector, aapsLogger, rxBus, aapsSchedulers, resourceHelper, constraintChecker, profileFunction, activePlugin, context, sp, buildHelper, dateUtil, repository, fabricPrivacy)
tempCommandQueue.readStatus(reason, callback)
tempCommandQueue.disposable.clear()
}
@Synchronized

View file

@ -1153,5 +1153,7 @@
<string name="key_ns_receive_cgm" translatable="false">ns_receive_cgm</string>
<string name="ns_receive_cgm">Receive/backfill CGM data</string>
<string name="ns_receive_cgm_summary">Accept CGM data from NS</string>
<string name="sms_timeout_while_wating">Timeout while waiting for finish of previous pump communication</string>
<string name="smscommunicator_another_bolus_in_queue">There is another bolus in queue. Try again later.</string>
</resources>

View file

@ -38,7 +38,7 @@ class MaintenancePluginTest : TestBase() {
sut = MaintenancePlugin(injector, context, resourceHelper, sp, nsSettingsStatus, aapsLogger, buildHelper, ConfigImpl(), fileListProvider, loggerUtils)
`when`(loggerUtils.suffix).thenReturn(".log.zip")
`when`(loggerUtils.logDirectory).thenReturn("src/test/res/logger")
`when`(fileListProvider.ensureExportDirExists()).thenReturn(File("src/test/res/logger"))
`when`(fileListProvider.ensureTempDirExists()).thenReturn(File("src/test/res/logger"))
}
@Test fun logFilesTest() {

View file

@ -56,7 +56,7 @@ class AuthRequestTest : TestBase() {
@Test fun doTests() {
val requester = Sms("aNumber", "aText")
val action: SmsAction = object : SmsAction() {
val action: SmsAction = object : SmsAction(false) {
override fun run() {
actionCalled = true
}

View file

@ -10,14 +10,14 @@ class SmsActionTest {
var result = ""
@Test fun doTests() {
var smsAction: SmsAction = object : SmsAction() {
var smsAction: SmsAction = object : SmsAction(false) {
override fun run() {
result = "A"
}
}
smsAction.run()
Assert.assertEquals(result, "A")
smsAction = object : SmsAction(1.0) {
smsAction = object : SmsAction(false, 1.0) {
override fun run() {
result = "B"
}
@ -25,7 +25,7 @@ class SmsActionTest {
smsAction.run()
Assert.assertEquals(result, "B")
Assert.assertEquals(smsAction.aDouble(), 1.0, 0.000001)
smsAction = object : SmsAction(1.0, 2) {
smsAction = object : SmsAction(false, 1.0, 2) {
override fun run() {
result = "C"
}
@ -34,7 +34,7 @@ class SmsActionTest {
Assert.assertEquals(result, "C")
Assert.assertEquals(smsAction.aDouble(), 1.0, 0.000001)
Assert.assertEquals(smsAction.secondInteger().toLong(), 2)
smsAction = object : SmsAction("aString", 3) {
smsAction = object : SmsAction(false, "aString", 3) {
override fun run() {
result = "D"
}
@ -43,7 +43,7 @@ class SmsActionTest {
Assert.assertEquals(result, "D")
Assert.assertEquals(smsAction.aString(), "aString")
Assert.assertEquals(smsAction.secondInteger().toLong(), 3)
smsAction = object : SmsAction(4) {
smsAction = object : SmsAction(false, 4) {
override fun run() {
result = "E"
}
@ -51,7 +51,7 @@ class SmsActionTest {
smsAction.run()
Assert.assertEquals(result, "E")
Assert.assertEquals(smsAction.anInteger().toLong(), 4)
smsAction = object : SmsAction(5, 6) {
smsAction = object : SmsAction(false, 5, 6) {
override fun run() {
result = "F"
}

View file

@ -86,6 +86,7 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() {
it.resourceHelper = resourceHelper
it.otp = otp
it.dateUtil = dateUtil
it.commandQueue = commandQueue
}
}
}
@ -262,7 +263,7 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() {
Assert.assertTrue(smsCommunicatorPlugin.isCommand("BOLUS", ""))
smsCommunicatorPlugin.messageToConfirm = null
Assert.assertFalse(smsCommunicatorPlugin.isCommand("BLB", ""))
smsCommunicatorPlugin.messageToConfirm = AuthRequest(injector, Sms("1234", "ddd"), "RequestText", "ccode", object : SmsAction() {
smsCommunicatorPlugin.messageToConfirm = AuthRequest(injector, Sms("1234", "ddd"), "RequestText", "ccode", object : SmsAction(false) {
override fun run() {}
})
Assert.assertTrue(smsCommunicatorPlugin.isCommand("BLB", "1234"))

View file

@ -12,7 +12,7 @@ buildscript {
rxkotlin_version = '2.4.0'
room_version = '2.3.0'
lifecycle_version = '2.3.1'
dagger_version = '2.36'
dagger_version = '2.37'
coroutinesVersion = '1.4.1'
activityVersion = '1.2.0'
fragmentktx_version = '1.3.0'
@ -28,12 +28,12 @@ buildscript {
work_version = '2.5.0'
junit_version = '4.13.2'
mockitoVersion = '3.10.0'
mockitoVersion = '3.11.1'
powermockVersion = '2.0.9'
dexmakerVersion = "1.2"
retrofit2Version = '2.9.0'
okhttp3Version = '4.9.0'
byteBuddyVersion = '1.11.0'
byteBuddyVersion = '1.11.3'
androidx_junit = '1.1.2'
androidx_rules = '1.4.0-alpha04'
@ -49,7 +49,7 @@ buildscript {
// see https://issuetracker.google.com/issues/162255866
classpath 'com.android.tools.build:gradle:4.1.3'
classpath 'com.google.gms:google-services:4.3.5'
classpath 'com.google.firebase:firebase-crashlytics-gradle:2.6.1'
classpath 'com.google.firebase:firebase-crashlytics-gradle:2.7.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files

View file

@ -27,6 +27,8 @@ interface IobCobCalculator {
fun iobArrayToString(array: Array<IobTotal>): String
fun convertToJSONArray(iobArray: Array<IobTotal>): JSONArray
fun clearCache()
/**
* Calculate CobInfo to now()
*

View file

@ -344,6 +344,21 @@ interface PumpSync {
**/
fun invalidateTemporaryBasal(id: Long): Boolean
/**
* Invalidate of temporary basals that failed to start
*
* If exists, isValid is set false
* If db record doesn't exist data is ignored and false returned
*
*
* @param pumpId pumpId of temporary basal
* @param pumpType pump type like PumpType.ACCU_CHEK_COMBO
* @param pumpSerial pump serial number
* @return true if running record is found and invalidated
**/
fun invalidateTemporaryBasalWithPumpId(pumpId: Long, pumpType: PumpType, pumpSerial: String): Boolean
/**
* Invalidate of temporary basals that failed to start
* MDT specific

View file

@ -31,6 +31,7 @@ class PrefFileListProvider @Inject constructor(
private val path = File(Environment.getExternalStorageDirectory().toString())
private val aapsPath = File(path, "AAPS" + File.separator + "preferences")
private val exportsPath = File(path, "AAPS" + File.separator + "exports")
private val tempPath = File(path, "AAPS" + File.separator + "temp")
private val extraPath = File(path, "AAPS" + File.separator + "extra")
companion object {
@ -103,6 +104,13 @@ class PrefFileListProvider @Inject constructor(
return exportsPath
}
fun ensureTempDirExists(): File {
if (!tempPath.exists()) {
tempPath.mkdirs()
}
return tempPath
}
fun ensureExtraDirExists(): File {
if (!extraPath.exists()) {
extraPath.mkdirs()
@ -115,7 +123,7 @@ class PrefFileListProvider @Inject constructor(
return File(aapsPath, timeLocal + "_" + config.FLAVOR + ".json")
}
fun newExportXmlFile(): File {
fun newExportCsvFile(): File {
val timeLocal = LocalDateTime.now().toString(DateTimeFormat.forPattern("yyyy-MM-dd'_'HHmmss"))
return File(exportsPath, timeLocal + "_UserEntry.csv")
}

View file

@ -330,6 +330,19 @@ class PumpSyncImplementation @Inject constructor(
}
}
override fun invalidateTemporaryBasalWithPumpId(pumpId: Long, pumpType: PumpType, pumpSerial: String): Boolean {
repository.runTransactionForResult(InvalidateTemporaryBasalTransactionWithPumpId(pumpId, pumpType.toDbPumpType(),
pumpSerial))
.doOnError { aapsLogger.error(LTag.DATABASE, "Error while invalidating TemporaryBasal", it) }
.blockingGet()
.also { result ->
result.invalidated.forEach {
aapsLogger.debug(LTag.DATABASE, "Invalidated TemporaryBasal $it")
}
return result.invalidated.size > 0
}
}
override fun invalidateTemporaryBasalWithTempId(temporaryId: Long): Boolean {
repository.runTransactionForResult(InvalidateTemporaryBasalWithTempIdTransaction(temporaryId))
.doOnError { aapsLogger.error(LTag.DATABASE, "Error while invalidating TemporaryBasal", it) }

View file

@ -168,6 +168,10 @@ class DanaFragment : DaggerFragment() {
binding.danaPumpstatuslayout.visibility = View.GONE
}
}, fabricPrivacy::logException)
binding.danaPumpstatus.text = ""
binding.danaPumpstatuslayout.visibility = View.GONE
@Suppress("SetTextI18n")
binding.btconnection.text = "{fa-bluetooth-b}"
updateGUI()
}
@ -191,14 +195,14 @@ class DanaFragment : DaggerFragment() {
val pump = danaPump
val plugin: Pump = activePlugin.activePump
if (pump.lastConnection != 0L) {
val agoMsec = System.currentTimeMillis() - pump.lastConnection
val agoMin = (agoMsec.toDouble() / 60.0 / 1000.0).toInt()
val agoMilliseconds = System.currentTimeMillis() - pump.lastConnection
val agoMin = (agoMilliseconds.toDouble() / 60.0 / 1000.0).toInt()
binding.lastconnection.text = dateUtil.timeString(pump.lastConnection) + " (" + resourceHelper.gs(R.string.minago, agoMin) + ")"
warnColors.setColor(binding.lastconnection, agoMin.toDouble(), 16.0, 31.0)
}
if (pump.lastBolusTime != 0L) {
val agoMsec = System.currentTimeMillis() - pump.lastBolusTime
val agoHours = agoMsec.toDouble() / 60.0 / 60.0 / 1000.0
val agoMilliseconds = System.currentTimeMillis() - pump.lastBolusTime
val agoHours = agoMilliseconds.toDouble() / 60.0 / 60.0 / 1000.0
if (agoHours < 6)
// max 6h back
binding.lastbolus.text = dateUtil.timeString(pump.lastBolusTime) + " " + dateUtil.sinceString(pump.lastBolusTime, resourceHelper) + " " + resourceHelper.gs(R.string.formatinsulinunits, pump.lastBolusAmount)

View file

@ -143,6 +143,27 @@ class BLEComm @Inject internal constructor(
fun disconnect(from: String) {
aapsLogger.debug(LTag.PUMPBTCOMM, "disconnect from: $from")
if (!encryptedDataRead && encryptedCommandSent && encryption == EncryptionType.ENCRYPTION_BLE5) {
// there was no response from pump after started encryption
// assume pairing keys are invalid
val lastClearRequest = sp.getLong(R.string.key_rs_last_clear_key_request, 0)
if (lastClearRequest != 0L && dateUtil.isOlderThan(lastClearRequest, 5)) {
ToastUtils.showToastInUiThread(context, R.string.invalidpairing)
danaRSPlugin.changePump()
sp.getStringOrNull(R.string.key_danars_address, null)?.let { address ->
bluetoothAdapter?.getRemoteDevice(address)?.let { device ->
try {
device::class.java.getMethod("removeBond").invoke(device)
} catch (e: Exception) {
aapsLogger.error("Removing bond has been failed. ${e.message}")
}
}
}
} else if (lastClearRequest == 0L) {
aapsLogger.error("Clearing pairing keys postponed")
sp.putLong(R.string.key_rs_last_clear_key_request, dateUtil.now())
}
}
if (!encryptedDataRead && encryptedCommandSent && encryption == EncryptionType.ENCRYPTION_RSv3) {
// there was no response from pump after started encryption
// assume pairing keys are invalid
@ -177,6 +198,30 @@ class BLEComm @Inject internal constructor(
}
@Synchronized fun close() {
/*
if (!encryptedDataRead && !encryptedCommandSent) {
// there was no response from pump before started encryption
// assume pairing is invalid
val lastClearRequest = sp.getLong(R.string.key_rs_last_clear_key_request, 0)
if (lastClearRequest != 0L && dateUtil.isOlderThan(lastClearRequest, 5)) {
ToastUtils.showToastInUiThread(context, R.string.invalidpairing)
danaRSPlugin.changePump()
sp.getStringOrNull(R.string.key_danars_address, null)?.let { address ->
bluetoothAdapter?.getRemoteDevice(address)?.let { device ->
try {
aapsLogger.debug(LTag.PUMPBTCOMM, "Removing bond")
device::class.java.getMethod("removeBond").invoke(device)
} catch (e: Exception) {
aapsLogger.error("Removing bond has been failed. ${e.message}")
}
}
}
} else if (lastClearRequest == 0L) {
aapsLogger.error("Clearing pairing keys postponed")
sp.putLong(R.string.key_rs_last_clear_key_request, dateUtil.now())
}
}
*/
aapsLogger.debug(LTag.PUMPBTCOMM, "BluetoothAdapter close")
bluetoothGatt?.close()
bluetoothGatt = null
@ -719,6 +764,10 @@ class BLEComm @Inject internal constructor(
processedMessage = message
val command = byteArrayOf(message.type.toByte(), message.opCode.toByte())
val params = message.getRequestParams()
if (bluetoothGatt == null) {
aapsLogger.debug(LTag.PUMPBTCOMM, ">>>>> IGNORING (NOT CONNECTED) " + message.friendlyName + " " + DanaRSPacket.toHexString(command) + " " + DanaRSPacket.toHexString(params))
return
}
aapsLogger.debug(LTag.PUMPBTCOMM, ">>>>> " + message.friendlyName + " " + DanaRSPacket.toHexString(command) + " " + DanaRSPacket.toHexString(params))
var bytes = bleEncryption.getEncryptedPacket(message.opCode, params, null)
// aapsLogger.debug(LTag.PUMPBTCOMM, ">>>>> " + DanaRS_Packet.toHexString(bytes))
@ -782,7 +831,7 @@ class BLEComm @Inject internal constructor(
aapsLogger.warn(LTag.PUMPBTCOMM, "Reply not received " + message.friendlyName)
message.handleMessageNotReceived()
}
// verify encryption for v3
// verify encryption for v3 & BLE
if (message is DanaRSPacketEtcKeepConnection)
if (!message.isReceived) disconnect("KeepAlive not received")
}

View file

@ -118,7 +118,7 @@ class DanaRSService : DaggerService() {
try {
val pump = activePlugin.activePump
rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.gettingpumpsettings)))
sendMessage(DanaRSPacketEtcKeepConnection(injector)) // test encryption for v3
sendMessage(DanaRSPacketEtcKeepConnection(injector)) // test encryption for v3 & BLE
sendMessage(DanaRSPacketGeneralGetShippingInformation(injector)) // serial no
sendMessage(DanaRSPacketGeneralGetPumpCheck(injector)) // firmware
sendMessage(DanaRSPacketBasalGetProfileNumber(injector))

View file

@ -0,0 +1,25 @@
package info.nightscout.androidaps.database.transactions
import info.nightscout.androidaps.database.embedments.InterfaceIDs
import info.nightscout.androidaps.database.entities.TemporaryBasal
class InvalidateTemporaryBasalTransactionWithPumpId(val pumpId: Long, val pumpType: InterfaceIDs.PumpType, val
pumpSerial:
String) :
Transaction<InvalidateTemporaryBasalTransactionWithPumpId.TransactionResult>() {
override fun run(): TransactionResult {
val result = TransactionResult()
val temporaryBasal = database.temporaryBasalDao.findByPumpIds(pumpId, pumpType, pumpSerial)
?: throw IllegalArgumentException("There is no such Temporary Basal with the specified temp ID.")
temporaryBasal.isValid = false
database.temporaryBasalDao.updateExistingEntry(temporaryBasal)
result.invalidated.add(temporaryBasal)
return result
}
class TransactionResult {
val invalidated = mutableListOf<TemporaryBasal>()
}
}

View file

@ -1433,7 +1433,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai
bolusID = insightDbHelper.getInsightBolusID(serial, event.getBolusID(), startTimestamp); // Line added to get id
if (event.getBolusType() == BolusType.STANDARD || event.getBolusType() == BolusType.MULTIWAVE) {
pumpSync.syncBolusWithPumpId(
bolusID.getTimestamp(),
startTimestamp,
event.getImmediateAmount(),
null,
bolusID.getId(),
@ -1443,9 +1443,9 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai
if (event.getBolusType() == BolusType.EXTENDED || event.getBolusType() == BolusType.MULTIWAVE) {
if (event.getDuration() > 0 && profileFunction.getProfile(bolusID.getTimestamp()) != null)
pumpSync.syncExtendedBolusWithPumpId(
bolusID.getTimestamp(),
startTimestamp,
event.getExtendedAmount(),
T.mins(event.getDuration()).msecs(),
timestamp - startTimestamp,
isFakingTempsByExtendedBoluses(),
bolusID.getId(),
PumpType.ACCU_CHEK_INSIGHT,

View file

@ -18,7 +18,7 @@ dependencies {
implementation project(':core')
//implementation project(':database')
implementation('com.thoughtworks.xstream:xstream:1.4.7') {
implementation('com.thoughtworks.xstream:xstream:1.4.17') {
exclude group: 'xmlpull', module: 'xmlpull'
}
}